Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

vb.net - How to specify long string literals in Visual Basic .NET?

Is there a way to conveniently store long string literal in Visual Basic source? I'm composing a console application with --help printout let's say 20 lines long.

Most welcome would be to have raw text area somewhere in source code where I can manage output text 1:1. Many languages supply HEREDOC functionality. In the VB, I couldn't find it. But maybe this could be tricked somehow via LINQ (XML)?

Thank you for good tips in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Update:

In VB.NET 14, which comes with Visual Studio 2015, all string literals support multiple lines. In VB.NET 14, all string literals work like verbatim string literals in C#. For instance:

Dim longString = "line 1
line 2
line 3"

Original Answer:

c# has a handy multi-line-string-literal syntax using the @ symbol (called verbatim strings), but unfortunately VB.NET does not have a direct equivalent to that (this is no longer true--see update above). There are several other options, however, that you may still find helpful.

Option 1: Simple Concatenation

Dim longString As String =
    "line 1" & Environment.NewLine &
    "line 2" & Environment.NewLine &
    "line 3"

Or the less .NET purist may choose:

Dim longString As String =
    "line 1" & vbCrLf &
    "line 2" & vbCrLf &
    "line 3"

Option 2: String Builder

Dim builder As New StringBuilder()
builder.AppendLine("line 1")
builder.AppendLine("line 2")
builder.AppendLine("line 3")
Dim longString As String = builder.ToString()

Option 3: XML

Dim longString As String = <x>line 1
line 2
line 3</x>.Value

Option 4: Array

Dim longString As String = String.Join(Environment.NewLine, {
    "line 1",
    "line 2",
    "line 3"})

Other Options

You may also want to consider other alternatives. For instance, if you really want it to be a literal in the code, you could do it in a small c# library of string literals where you could use the @ syntax. Or, you may decide that having it in a literal isn't really necessary and storing the text as a string resource would be acceptable. Or, you could also choose to store the string in an external data file and load it at run-time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...