【问题标题】:What's the differences between "{0}" and "&" in VB.NET?VB.NET 中的“{0}”和“&”有什么区别?
【发布时间】:2019-06-29 19:01:11
【问题描述】:

伙计们,我还在学习,请放轻松。

以下代码:

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
你好,约翰
你好,1
你好,约翰
5 + 5 = 10

我到处找,找不到答案。
何时使用“{0}、{1}、...等”?以及何时使用"&"
哪个更好?为什么?

【问题讨论】:

  • 连接两个字符串,而不是在任何给定点替换字符串中的变量。
  • [这篇文章][1] 也有一些很好的答案(在 C# 上下文中)。 [1]:stackoverflow.com/questions/296978/…

标签: vb.net concatenation


【解决方案1】:

{0} 是指定格式占位符,而 & 只是连接字符串。

使用格式占位符

Dim name As String = String.Format("{0} {1}", "James", "Johnson")

使用字符串连接

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

【讨论】:

    【解决方案2】:

    您在这里看到的是两个非常不同的表达式,它们恰好对相同的输出求值。

    VB.Net 中的& 运算符是字符串连接运算符。它本质上是通过将表达式的左侧和右侧都转换为 String 并将它们加在一起来工作的。这意味着以下所有操作大致等效

    "Hello " & num
    "Hello " & num.ToString()
    "Hello " & CStr(num)
    

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

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

    您看到相同输出的原因是因为将{0} 放在字符串末尾几乎与两个值的字符串连接完全相同。

    【讨论】:

      【解决方案3】:

      使用{N} 称为Composite Formatting。除了可读性之外,一个优点是您可以轻松设置对齐和格式属性。来自 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
      

      【讨论】:

        【解决方案4】:

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

        使用concatenation的问题是每次concat操作都会创建一个新的string,会消耗内存。

        如果您要执行大量替换,那么最好的性能是使用 System.Text.StringBuilder 代替。

        【讨论】:

          猜你喜欢
          • 2016-02-19
          • 2011-04-21
          • 2016-03-23
          • 2021-06-16
          • 2010-09-23
          • 2012-09-23
          • 2021-02-13
          • 2012-08-02
          相关资源
          最近更新 更多