如何在 Visual Basic .NET 中指定长字符串文字? [英] How to specify long string literals in Visual Basic .NET?

查看:28
本文介绍了如何在 Visual Basic .NET 中指定长字符串文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以方便地在 Visual Basic 源代码中存储长字符串文字?我正在编写一个带有 --help 打印输出的控制台应用程序,假设有 20 行长.

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.

最受欢迎的是在我可以管理的源代码中的某个地方有原始文本区域输出文本 1:1.许多语言提供 HEREDOC 功能.在VB中,我找不到它.但也许这可以通过 LINQ (XML) 以某种方式被欺骗?

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)?

提前感谢您的好提示!

推荐答案

更新:

在 Visual Studio 2015 附带的 VB.NET 14 中,所有字符串文字都支持多行.在 VB.NET 14 中,所有字符串文字的工作方式都类似于 C# 中的verbatim 字符串文字.例如:

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"

<小时>

原答案:

c# 有一个使用 @ 符号(称为 verbatim strings)的方便的多行字符串文字语法,但不幸的是 VB.NET 没有直接等效的到那个(这不再是真的 - 请参阅上面的更新).但是,还有其他几个选项可能对您有帮助.


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.

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

或者较少的 .NET 纯粹主义者可以选择:

Or the less .NET purist may choose:

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

选项 2:字符串生成器

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

选项 3:XML

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

选项 4:数组

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

其他选项

您可能还想考虑其他替代方案.例如,如果您真的希望它成为代码中的文字,您可以在一个小型的 c# 字符串文字库中使用 @ 语法来实现.或者,您可能决定将它放在文字中并不是真正必要的,并且将文本存储为字符串资源是可以接受的.或者,您也可以选择将字符串存储在外部数据文件中并在运行时加载.

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.

这篇关于如何在 Visual Basic .NET 中指定长字符串文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆