在VB.NET中,“{0}”和“&”有什么区别?

4
请大家多包涵,因为我还在学习中。
以下代码:
Imports System.Console

Module Module1

    Sub Main()
        Dim num As Integer
        Dim name As String

        num = 1
        name = "John"

        WriteLine("Hello, {0}", num)
        WriteLine("Hello, {0}", name)
        WriteLine("Hello, {0}", 1)
        WriteLine("Hello, {0}", "John")
        WriteLine("5 + 5 = {0}", 5 + 5)

        WriteLine()
    End Sub

End Module

以下代码具有相同的输出:

Imports System.Console

    Module Module1

        Sub Main()
            Dim num As Integer
            Dim name As String

            num = 1
            name = "John"

            WriteLine("Hello, " & num)
            WriteLine("Hello, " & name)
            WriteLine("Hello, " & 1)
            WriteLine("Hello, " & "John")
            WriteLine("5 + 5 = " & 5 + 5)

            WriteLine()
        End Sub

    End Module

两个输出结果都是:

你好,1
你好,John
你好,1
你好,John
5 + 5 = 10

我到处查找,但找不到答案。
何时使用"{0}, {1}, ... etc"?何时使用"&"
哪一个更好?为什么?


1
将两个字符串连接起来,与在任意给定点替换字符串中的变量有所不同。 - Mike McMahon
2
这篇帖子(在C#上下文中)也有一些很好的答案。 - dizzwave
4个回答

6
使用 {0},你可以指定一个格式占位符;而使用 &,则只是简单地连接字符串。 使用格式占位符
Dim name As String = String.Format("{0} {1}", "James", "Johnson")

使用字符串连接

Dim name As String = "James" & " " & "Johnson"

5
你看到的是两个非常不同的表达式,它们恰好评估为相同的输出。
在VB.Net中,&运算符是字符串连接运算符。 它基本上通过将表达式的左侧和右侧转换为String并将它们加在一起来工作。 这意味着下面所有的操作大致等效。
"Hello " & num
"Hello " & num.ToString()
"Hello " & CStr(num)

{0}是.Net APIs的一个特性。它表示字符串中的一个位置,稍后将被替换为一个值。{0}代表传递给函数的第一个值,{1}代表第二个值,依此类推。这意味着下面的所有操作大致等效。

Console.WriteLine("Hello {0}!", num)
Console.WriteLine("Hello " & num & "!")

你看到相同的输出是因为在字符串末尾放置 {0} 几乎与将两个值连接成一个字符串相同。

4

使用{N}被称为复合格式化。除了可读性外,另一个优点是您可以轻松设置对齐和格式属性。以下是来自MSDN链接的示例:

Dim MyInt As Integer = 100
Console.WriteLine("{0:C}", MyInt)
' The example displays the following output
' if en-US is the current culture:
'        $100.00

2

{0}是一个占位符,与String.Format一起使用,以便进行更可读和性能更佳的字符串替换。包括WriteLine在内的几个方法调用都隐含调用了String.Format。

使用连接的问题在于每个连接操作都会创建一个新字符串,这会消耗内存。

如果您正在执行大量的替换操作,则最佳性能是使用System.Text.StringBuilder


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