string VB.NET 中的多行字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/706382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:24:49  来源:igfitidea点击:

Multiline strings in VB.NET

stringvb.net

提问by pistacchio

Is there a way to have multiline strings in VB.NET like Python

有没有办法像 Python 一样在 VB.NET 中拥有多行字符串

a = """
multi
line
string
"""

or PHP?

或PHP?

$a = <<<END
multi
line
string
END;

Of course something that is not

当然不是的东西

"multi" & _
"line

回答by Vincenzo Alcamo

You can use XML Literalsto achieve a similar effect:

您可以使用XML 文字来实现类似的效果:

Imports System.XML
Imports System.XML.Linq
Imports System.Core

Dim s As String = <a>Hello
World</a>.Value

Remember that if you have special characters, you should use a CDATA block:

请记住,如果您有特殊字符,则应使用 CDATA 块:

Dim s As String = <![CDATA[Hello
World & Space]]>.Value


2015 UPDATE:

2015年更新:

Multi-line string literals were introduced in Visual Basic 14(in Visual Studio 2015). The above example can be now written as:

Visual Basic 14(在Visual Studio 2015 中)中引入了多行字符串文字。上面的例子现在可以写成:

Dim s As String = "Hello
World & Space"

MSDN article isn't updated yet (as of 2015-08-01), so check some answers below for details.

MSDN article isn't updated yet (as of 2015-08-01), so check some answers below for details.

Details are added to the Roslyn New-Language-Features-in-VB-14Github repository.

详细信息已添加到Roslyn New-Language-Features-in-VB-14Github 存储库中。

回答by JaredPar

VB.Net has no such feature and it will notbe coming in Visual Studio 2010. The feature that jirwin is refering is called implicit line continuation. It has to do with removing the _ from a multi-line statement or expression. This does remove the need to terminate a multiline string with _ but there is still no mult-line string literal in VB.

VB.Net 没有这样的功能,它不会出现在 Visual Studio 2010 中。 jirwin 所指的功能称为隐式行延续。它与从多行语句或表达式中删除 _ 有关。这确实消除了用 _ 终止多行字符串的需要,但在 VB 中仍然没有多行字符串文字。

Example for multiline string

多行字符串示例

Visual Studio 2008

视觉工作室 2008

Dim x = "line1" & vbCrlf & _
        "line2"

Visual Studio 2010

视觉工作室 2010

Dim x = "line1" & vbCrlf & 
        "line2"

回答by ozzy432836

I used this variant:

我使用了这个变体:

     Dim query As String = <![CDATA[
        SELECT 
            a.QuestionID
        FROM 
            CR_Answers a

        INNER JOIN 
            CR_Class c ON c.ClassID = a.ClassID
        INNER JOIN
            CR_Questions q ON q.QuestionID = a.QuestionID
        WHERE 
            a.CourseID = 1
        AND 
            c.ActionPlan = 1
        AND q.Q_Year = '11/12'
        AND q.Q_Term <= (SELECT CurrentTerm FROM CR_Current_Term)
    ]]>.Value()

it allows < > in the string

它允许 < > 在字符串中

回答by miroxlav

Multi-line strings are available since the Visual Studio 2015.

多行字符串自 Visual Studio 2015 起可用。

Dim sql As String = "
    SELECT ID, Description
    FROM inventory
    ORDER BY DateAdded
"

You can combine them with string interpolationto maximize usefullness:

您可以将它们与字符串插值结合使用,以最大限度地提高实用性:

Dim primaryKey As String = "ID"
Dim inventoryTable As String = "inventory"

Dim sql As String = $"
    SELECT {primaryKey}, Description
    FROM {inventoryTable}
    ORDER BY DateAdded
"

Note that interpolated strings begin with $and you need to take care of ", {and }contained inside – convert them into "", {{or }}respectively.

请注意,内插字符串以 开头,$您需要处理",{}包含在其中 - 将它们分别转换为"",{{}}

Here you can see actual syntax highlightingof interpolated parts of the above code example:

在这里您可以看到上述代码示例的内插部分的实际语法突出显示

enter image description here

在此处输入图片说明

If you wonder if their recognition by the Visual Studio editor also works with refactoring (e.g. mass-renaming the variables), then you are right, code refactoring works with these.Not mentioning that they also support IntelliSense, reference counting or code analysis.

如果您想知道 Visual Studio 编辑器对它们的识别是否也适用于重构(例如批量重命名变量),那么您是对的,代码重构适用于这些。更不用说它们还支持 IntelliSense、引用计数或代码分析。

回答by Lucian Wischik

Multiline string literals are introduced in Visual Basic 14.0 - https://roslyn.codeplex.com/discussions/571884

Visual Basic 14.0 中引入了多行字符串文字 - https://roslyn.codeplex.com/discussions/57188​​4

You can use then in the VS2015 Preview, out now - http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs(note that you can still use VS2015 even when targeting an older version of the .NET framework)

您可以在 VS2015 预览版中使用,现在推出 - http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs(请注意,即使针对较旧的版本,您仍然可以使用 VS2015 .NET 框架的版本)

Dim multiline = "multi
line
string"

VB strings are basically now the same as C# verbatim strings - they don't support backslash escape sequences like \n, and they do allow newlines within the string, and you escape the quote symbol with double-quotes ""

VB 字符串现在基本上与 C# 逐字字符串相同 - 它们不支持像 \n 这样的反斜杠转义序列,并且它们允许在字符串中使用换行符,并且您可以使用双引号 "" 转义引号符号

回答by Destructerator

this was a really helpful article for me, but nobody mentioned how to concatenatein case you want to send some variables, which is what you need to do 99% of the time.

这对我来说是一篇非常有用的文章,但没有人提到如何连接以防万一你想发送一些变量,这是你 99% 的时间需要做的。

... <%=variable %>...

... <%=变量%>...

Here's how you do it:

以下是您的操作方法:

<SQL> SELECT * FROM MyTable WHERE FirstName='<%= EnteredName %>' </SQL>.Value

<SQL> SELECT * FROM MyTable WHERE FirstName='<%= EnteredName %>' </SQL>.Value

回答by RichardJohnn

Well, since you seem to be up on your python, may I suggest that you copy your text into python, like:

好吧,既然你似乎对你的 python 感兴趣,我可以建议你将文本复制到 python 中,例如:

 s="""this is gonna 
last quite a 
few lines"""

then do a:

然后做一个:

  for i in s.split('\n'):
    print 'mySB.AppendLine("%s")' % i

#    mySB.AppendLine("this is gonna")
#    mySB.AppendLine("last quite a")
#    mySB.AppendLine("few lines")

or

或者

  print ' & _ \n'.join(map(lambda s: '"%s"' % s, s.split('\n')))

#    "this is gonna" & _ 
#    "last quite a" & _ 
#    "few lines"

then at least you can copy that out and put it in your VB code. Bonus points if you bind a hotkey (fastest to get with:Autohotkey) to do this for for whatever is in your paste buffer. The same idea works well for a SQL formatter.

那么至少您可以将其复制出来并将其放入您的VB代码中。如果您绑定一个热键(最快获得:Autohotkey)来为粘贴缓冲区中的任何内容执行此操作,则奖励积分。同样的想法适用于 SQL 格式化程序。

回答by windchaser

Multi-line string literals in vb.net using the XElement class.

vb.net 中使用 XElement 类的多行字符串文字。

Imports System.Xml.Linq

Public Sub Test()

dim sOderBy as string = ""

dim xe as XElement = <SQL>
                SELECT * FROM <%= sTableName %>
                 <ORDER_BY> ORDER BY <%= sOrderBy %></ORDER_BY>
                 </SQL>

'** conditionally remove a section 
if sOrderBy.Length = 0 then xe.<ORDER BY>.Remove

'** convert XElement value to a string 
dim sSQL as String = xe.Value

End Sub

回答by Osiname

To me that is the most annoying thing about VB as a language. Seriously, i once wrote the string in a file and wrote code something along the lines of:

对我来说,这是 VB 作为一种语言最烦人的事情。说真的,我曾经在一个文件中写过这个字符串,并写了一些类似的代码:

Dim s as String = file_get_contents("filename.txt")

just so i could test the query directly on SQL server if i need to.

如果需要,我可以直接在 SQL 服务器上测试查询。

My current method is to use a stored procedure on the SQL Server and just call that so i can pass in parameters to the query, etc

我目前的方法是在 SQL Server 上使用存储过程并调用它,以便我可以将参数传递给查询等

回答by Nelson

I figured out how to use both <![CDATA[ along with <%= for variables, which allows you to code without worry.

我想出了如何同时使用 <![CDATA[ 和 <%= 变量,这让您可以放心地编码。

You basically have to terminate the CDATA tags before the VB variable and then re-add it after so the CDATA does not capture the VB code. You need to wrap the entire code block in a tag because you will you have multiple CDATA blocks.

您基本上必须在 VB 变量之前终止 CDATA 标记,然后在之后重新添加它,这样 CDATA 就不会捕获 VB 代码。您需要将整个代码块包装在一个标签中,因为您将拥有多个 CDATA 块。

Dim script As String = <code><![CDATA[
  <script type="text/javascript">
    var URL = ']]><%= domain %><![CDATA[/mypage.html';
  </script>]]>
</code>.value