简体   繁体   English

VB.NET 中的多行字符串

[英]Multiline strings in VB.NET

Is there a way to have multiline strings in VB.NET like Python有没有办法在 VB.NET 中使用多行字符串,例如 Python

a = """
multi
line
string
"""

or PHP?还是 PHP?

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

Of course something that is not当然不是

"multi" & _
"line

You can use XML Literals to 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 ). Visual Basic 14 (在Visual Studio 2015中)中引入了多行字符串文字。 The above example can be now written as:上面的例子现在可以写成:

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.

Details are added to the Roslyn New-Language-Features-in-VB-14 Github repository.详细信息已添加到Roslyn New-Language-Features-in-VB-14 Github 存储库中。

VB.Net has no such feature and it will not be coming in Visual Studio 2010. The feature that jirwin is refering is called implicit line continuation. VB.Net 没有这样的功能,它不会出现在 Visual Studio 2010 中。jirwin 所指的功能称为隐式行延续。 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 中仍然没有多行字符串文字。

Example for multiline string多行字符串示例

Visual Studio 2008视觉工作室 2008

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

Visual Studio 2010视觉工作室 2010

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

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它允许 < > 在字符串中

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 interpolation to 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 highlighting of interpolated parts of the above code example:在这里,您可以看到上述代码示例的插值部分的实际语法突出显示

在此处输入图像描述

If you wonder if their recognition by the Visual Studio editor also works with refactoring (eg mass-renaming the variables), then you are right, code refactoring works with these.如果您想知道 Visual Studio 编辑器对它们的识别是否也适用于重构(例如批量重命名变量),那么您是对的,代码重构适用于这些。 Not mentioning that they also support IntelliSense, reference counting or code analysis.更不用说它们还支持 IntelliSense、引用计数或代码分析。

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/571884

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 这样的反斜杠转义序列,并且它们允许字符串中包含换行符,并且您可以使用双引号 "" 转义引号符号

this was a really helpful article for me, but nobody mentioned how to concatenate in 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

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.那么至少您可以将其复制出来并将其放入您的VB代码中。 Bonus points if you bind a hotkey (fastest to get with: Autohotkey ) to do this for for whatever is in your paste buffer.如果您绑定热键(最快获得: Autohotkey )为粘贴缓冲区中的任何内容执行此操作,则会获得奖励积分。 The same idea works well for a SQL formatter.同样的想法适用于 SQL 格式化程序。

Multi-line string literals in vb.net using the XElement class. vb.net 中的多行字符串文字使用 XElement class。

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

To me that is the most annoying thing about VB as a language.对我来说,这是 VB 作为一门语言最烦人的地方。 Seriously, i once wrote the string in a file and wrote code something along the lines of:说真的,我曾经将字符串写在一个文件中,并编写了如下代码:

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 服务器上使用存储过程,然后调用它,这样我就可以将参数传递给查询等

I figured out how to use both <,[CDATA[ along with <%= for variables.我想出了如何将 <,[CDATA[ 与 <%= 一起用于变量。 which allows you to code without worry.这使您可以放心编码。

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.您基本上必须在 VB 变量之前终止 CDATA 标记,然后在之后重新添加它,这样 CDATA 就不会捕获 VB 代码。 You need to wrap the entire code block in a tag because you will you have multiple CDATA blocks.您需要将整个代码块包装在标签中,因为您将拥有多个 CDATA 块。

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

Disclaimer: I love python.免责声明:我喜欢 python。 It's multi-line strings are only one reason.它的多行字符串只是原因之一。

But I also do VB.Net, so here's my short-cut for more readable long strings.但我也做 VB.Net,所以这是我的更易读的长字符串的捷径。

  Dim lines As String() = {
    "Line 1",
    "Line 2",
    "Line 3"
  }
  Dim s As String = Join(lines, vbCrLf)

You could (should?) put the string in a resource-file (eg "My Project"/Resources) and then get it with您可以(应该?)将字符串放入资源文件(例如“我的项目”/Resources)中,然后使用

 Dim a = My.Resources.Whatever_you_chose

you can use XML for this like你可以像这样使用 XML

dim vrstr as string = <s>
    some words
    some words
    some
    words
</s>

in Visual studio 2010 (VB NET)i try the following and works fine在 Visual Studio 2010(VB NET)中,我尝试以下并正常工作

Dim HtmlSample As String = <anything>what ever you want to type here with multiline strings</anything>

dim Test1 as string =<a>onother multiline example</a>

Available in Visual Basic 14 as part of Visual Studio 2015 https://msdn.microsoft.com/en-us/magazine/dn890368.aspx在 Visual Basic 14 中作为 Visual Studio 2015 的一部分提供https://msdn.microsoft.com/en-us/magazine/dn890368.aspx

But not yet supported by R#.但 R# 尚不支持。 The good news is they will be supported soon!好消息是他们很快就会得到支持! Please vote on Youtrack to notify JetBrains you need them also.请在Youtrack上投票以通知 JetBrains 您也需要它们。

If you need an XML literal in VB.Net with an line code variable, this is how you would do it:如果您需要 VB.Net 中的 XML 文字和行代码变量,您可以这样做:

<Tag><%= New XCData(T.Property) %></Tag>

You can also use System.Text.StringBuilder class in this way:您也可以通过这种方式使用System.Text.StringBuilder class:

Dim sValue As New System.Text.StringBuilder
sValue.AppendLine("1st Line")
sValue.AppendLine("2nd Line")
sValue.AppendLine("3rd Line")

Then you get the multiline string using:然后你得到多行字符串使用:

sValue.ToString()

Since this is a readability issue, I have used the following code:由于这是一个可读性问题,我使用了以下代码:

MySql = ""
MySql = MySql & "SELECT myTable.id"
MySql = MySql & " FROM myTable"
MySql = MySql & " WHERE myTable.id_equipment = " & lblId.Text

Use vbCrLf or vbNewLine .使用vbCrLfvbNewLine It works with MessageBoxes and many other controls I tested.它适用于 MessageBoxes 和我测试过的许多其他控件。

Dim str As String
str = "First line" & vbCrLf & "Second line"
MsgBox(str)
str = "First line" & vbNewLine & "Second line"
MsgBox(str)

It will show two identical MessageBoxes with 2 lines.它将显示两个相同的带有 2 行的 MessageBox。

No, VB.NET does not yet have such a feature.不,VB.NET 还没有这个功能。 It will be available in the next iteration of VB (visual basic 10) however ( link )它将在 VB(visual basic 10)的下一次迭代中可用,但是( 链接

if it's like C# (I don't have VB.Net installed) you can prefix a string with @如果它像 C# (我没有安装 VB.Net)你可以在字符串前面加上 @

foo = @"Multiline
String"

this is also useful for things like @"C:\Windows\System32\" - it essentially turns off escaping and turns on multiline.这对于 @"C:\Windows\System32\" 之类的东西也很有用——它实际上关闭了 escaping 并打开了多行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM