VB.NET是否有与C#等价的多行字符串声明语法?

7

可能是重复问题:
VB.NET中的多行字符串

在c#中,你可以这样写:

string s = @"hello
there
mister";

VB.NET是否有类似的方法而不涉及字符串连接?我想能够在两个双引号之间粘贴多行文本。但我不相信VB.NET支持这一点。


在VB.NET 14中,您现在可以执行字符串插值 - 因此: dim multiline = $"Multiliine String!" - Luke T O'Brien
@LukeTO'Brien 在新的VB中,你实际上甚至不需要插值。 - oscilatingcretin
4个回答

15

编辑:VS2015及以上版本

现在你可以通过以下方式来实现多行字符串:

Dim text as String = "
This
Is
Multiline
Text!"

VB .NET 中没有多行字符串文本 - 最接近的方式是使用拼接来实现(不使用 LINQ)。

在 VS2010 之前:

Dim x = "some string" & vbCrlf & _
        "the rest of the string"

2010年后发布的内容:

Dim x = "some string" & vbCrlf &
        "the rest of the string"

XML/LINQ 的技巧是:

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

Dim x As String = <a>Some code
and stuff</a>.Value

但这会限制你在 <a></a> 块中可以放置哪些字符,因为涉及到 XML 语义。如果你需要使用特殊字符,请将文本包含在标准的 CDATA 块中:

Dim x As String = <a><![CDATA[Some code
& stuff]]></a>.Value

我相信字符串插值 https://msdn.microsoft.com/zh-cn/library/dn961160.aspx 可以用于多行。 - Luke T O'Brien
你能否更新这个答案,因为VB.NET 14支持多行文字了:https://msdn.microsoft.com/en-gb/magazine/dn890368.aspx - Giles Bathgate

5
不可以,但你可以使用像这样的xml技巧:

Dim s As String = <a>hello
there
mister</a>.Value

或者将您的字符串放入项目资源中。


2

我不确定这是否是最好的做法,但我认为没有等价的运算符。

Dim myString As String =
"Hello" & Environment.NewLine & "there" & Environment.NewLine & "mister"

我认为Environement.NewLine会根据操作系统自动选择正确的换行符。

编辑:我刚刚看到您想要直接在代码中插入多行文本,因此还有另一种可能的解决方案:

您仍然需要使用字符串引号和逗号,但是以下是示例:

    Dim myList as new List(of String) (new String(){
        "Hello",
        "there",
        "mister"
    })

    Dim result as String

    For Each bob as String In myList
        result += bob & Environment.NewLine
    next

不幸的是,这个解决方案仍然不能满足我的最初要求:“我想能够在两个双引号之间粘贴多行文本”。为了再次将这个字符串数组组合在一起,我仍然必须依靠某种形式的连接,无论是在“VbCrLf”处连接数组还是在循环中使用“&=”。谢谢。 - oscilatingcretin

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接