内插字符串(Visual Basic 引用)Interpolated Strings (Visual Basic Reference)

用于构造字符串。Used to construct strings. 内插字符串类似于包含内插表达式的模板字符串。An interpolated string looks like a template string that contains interpolated expressions. 内插字符串返回的字符串可替换内插表达式并且包含其字符串表示形式。An interpolated string returns a string that replaces the interpolated expressions that it contains with their string representations. 此功能在 Visual Basic 14 及更高版本中可用。This feature is available in Visual Basic 14 and later versions.

复合格式字符串相比,内插字符串的参数更易于理解。The arguments of an interpolated string are easier to understand than a composite format string. 例如,内插字符串For example, the interpolated string

Console.WriteLine($"Name = {name}, hours = {hours:hh}")

包含 2 个内插表达式:“{name}”和“{hours:hh}”。contains two interpolated expressions, '{name}' and '{hours:hh}'. 等效的复合格式字符串为:The equivalent composite format string is:

Console.WriteLine("Name = {0}, hours = {1:hh}", name, hours)

内插字符串的结构为:The structure of an interpolated string is:

$"<text> {<interpolated-expression> [,<field-width>] [:<format-string>] } <text> ..."

其中:where:

  • field-width 是一个带符号整数,表示字段中的字符数。field-width is a signed integer that indicates the number of characters in the field. 如果为正数,则字段右对齐;如果为负数,则左对齐。If it is positive, the field is right-aligned; if negative, left-aligned.

  • “格式字符串”是适合正在设置格式的对象类型的格式字符串。format-string is a format string appropriate for the type of object being formatted. 例如,对于 DateTime 值,它可以是标准日期和时间格式字符串,例如 "d" 或 "d"。For example, for a DateTime value, it could be a standard date and time format string such as "D" or "d".

重要

字符串开头的 $" 之间不能有任何空格。You cannot have any white space between the $ and the " that starts the string. 这样做会导致编译器错误。Doing so causes a compiler error.

可以在可使用字符串的任何位置使用内插字符串。You can use an interpolated string anywhere you can use a string literal. 每次执行带内插字符串的代码时,都会计算内插字符串。The interpolated string is evaluated each time the code with the interpolated string executes. 这有助于分隔内插字符串的定义和计算结果。This allows you to separate the definition and evaluation of an interpolated string.

若要在内插字符串中包含大括号(“{”或“}”),请使用两个大括号,即“{{”或“}}”。To include a curly brace ("{" or "}") in an interpolated string, use two curly braces, "{{" or "}}". 请参阅“隐式转换”部分以获取详细信息。See the Implicit Conversions section for more details.

如果内插字符串包含在内插字符串中具有特殊意义的其他字符,例如引号 (")、冒号 (:) 或逗号 (,),则出现在文本中时应转义这些字符;如果它们是内插表达式中随附的语言元素,则应将其包括在由括号分隔的表达式内。If the interpolated string contains other characters with special meaning in an interpolated string, such as the quotation mark ("), colon (:), or comma (,), they should be escaped if they occur in literal text, or they should be included in an expression delimited by parentheses if they are language elements included in an interpolated expression. 以下示例转义了引号以将其包括在结果字符串中,并使用括号来分隔表达式 (age == 1 ? "" : "s"),以防冒号被解读为格式字符串的开头。The following example escapes quotation marks to include them in the result string, and it uses parentheses to delimit the expression (age == 1 ? "" : "s") so that the colon is not interpreted as beginning a format string.

Public Module Example
   Public Sub Main()
      Dim name = "Horace"
      Dim age = 34
      Dim s1 = $"He asked, ""Is your name {name}?"", but didn't wait for a reply."
      Console.WriteLine(s1)
      
      Dim s2 = $"{name} is {age:D3} year{(If(age = 1, "", "s"))} old."
      Console.WriteLine(s2) 
   End Sub
End Module
' The example displays the following output:
'       He asked, "Is your name Horace?", but didn't wait for a reply.
'       Horace is 034 years old.
' </Snippet1>

隐式转换Implicit Conversions

内插字符串有 3 种隐式类型转换:There are three implicit type conversions from an interpolated string:

  1. 将内插字符串转换为 StringConversion of an interpolated string to a String. 下例返回一个字符串,其内插字符串表达式已替换为字符串表示形式。The following example returns a string whose interpolated string expressions have been replaced with their string representations. 例如:For example:

    Public Module Example
       Public Sub Main()
          Dim name = "Bartholomew"
          Dim s1 = $"Hello, {name}!"  
          Console.WriteLine(s1)
       End Sub
    End Module
    ' The example displays the following output:
    '      Hello, Bartholomew!
    ' </Snippet1>
    

    这是字符串解释的最终结果。This is the final result of a string interpretation. 出现的所有双大括号(“{{”和“}}”)都转换为单大括号。All occurrences of double curly braces ("{{" and "}}") are converted to a single curly brace.

  2. 将内插字符串转换为 IFormattable 变量,使用此变量可通过单个 IFormattable 实例创建多个包含区域性特定内容的结果字符串。Conversion of an interpolated string to an IFormattable variable that allows you create multiple result strings with culture-specific content from a single IFormattable instance. 对于包括诸如各区域性的正确数字和日期格式之类的内容,这种转换很有用。This is useful for including such things as the correct numeric and date formats for individual cultures. 出现的所有双大括号(“{{”和“}}”)仍保留为双大括号,直至通过显式或隐式调用 ToString() 方法格式化字符串。All occurrences of double curly braces ("{{" and "}}") remain as double curly braces until you format the string by explicitly or implicitly calling the ToString() method. 所有包含的内插表达式都转换为 {0}、{1}等。All contained interpolation expressions are converted to {0}, {1}, and so on.

    以下示例使用反射来显示内插字符串中所创建的 IFormattable 变量的成员以及字段和属性值。The following example uses reflection to display the members as well as the field and property values of an IFormattable variable that is created from an interpolated string. 并将 IFormattable 变量传递给 Console.WriteLine(String) 方法。It also passes the IFormattable variable to the Console.WriteLine(String) method.

    Imports System.Globalization
    Imports System.Reflection
    
    Public Module Example
       Public Sub Main()
          Dim price = 1000
          Dim s2 As IFormattable = $"The cost of this item is {price:C}."  
          ShowInfo(s2)
          CultureInfo.CurrentCulture = New CultureInfo("en-US")
          Console.WriteLine(s2)
          CultureInfo.CurrentCulture = New CultureInfo("fr-FR")
          Console.WriteLine(s2)      
       End Sub
    
       Private Sub ShowInfo(obj As Object)
          Console.WriteLine($"Displaying member information:{vbCrLf}")
          Dim t = obj.GetType()
          Dim flags = BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.Static Or BindingFlags.NonPublic
          For Each m In t.GetMembers(flags) 
             Console.Write($"   {m.Name} {m.MemberType}")   
             If m.MemberType = MemberTypes.Property Then
                Dim p = t.GetProperty(m.Name, flags)
                Console.Write($"   Value: {p.GetValue(obj)}")         
             End If
             If m.MemberType = MemberTypes.Field Then
                Dim f = t.GetField(m.Name, flags)
                Console.Write($"   Value: {f.GetValue(obj)}")
             End If
             Console.WriteLine()
          Next
          Console.WriteLine($"-------{vbCrLf}")
       End Sub
    End Module
    ' The example displays the following output:
    Displaying member information:
    
    '       get_Format Method
    '       GetArguments Method
    '       get_ArgumentCount Method
    '       GetArgument Method
    '       ToString Method
    '       System.IFormattable.ToString Method
    '       ToString Method
    '       Equals Method
    '       GetHashCode Method
    '       GetType Method
    '       Finalize Method
    '       MemberwiseClone Method
    '       .ctor Constructor
    '       Format Property   Value: The cost of this item is {0:C}.
    '       ArgumentCount Property   Value: 1
    '       _format Field   Value: The cost of this item is {0:C}.
    '       _arguments Field   Value: System.Object[]
    '       -------
    '
    '       The cost of this item is $1,000.00.
    '       The cost of this item is 1 000,00 €.
    ' </Snippet1>
    
    

    请注意,只能通过使用反射来检查内插字符串。Note that the interpolated string can be inspected only by using reflection. 如果将其传递给字符串格式设置方法,例如 WriteLine(String),则会解析其格式项并返回结果字符串。If it is passed to a string formatting method, such as WriteLine(String), its format items are resolved and the result string returned.

  3. 将内插字符串转换为表示复合格式字符串的 FormattableString 变量。Conversion of an interpolated string to a FormattableString variable that represents a composite format string. 例如,检查复合格式字符串及其呈现为结果字符串的方式可能有助于在生成查询时防止注入攻击。Inspecting the composite format string and how it renders as a result string might, for example, help you protect against an injection attack if you were building a query. FormattableString 还包括:A FormattableString also includes:

    出现的所有双大括号("{{" 和 "}}")都保留为双大括号,直至你进行格式化。All occurrences of double curly braces ("{{" and "}}") remain as double curly braces until you format. 所有包含的内插表达式都转换为 {0}、{1}等。All contained interpolation expressions are converted to {0}, {1}, and so on.

    Imports System.Globalization
    
    Public Module Example
       Public Sub Main()
          Dim name = "Bartholomew"
          Dim s3 As FormattableString = $"Hello, {name}!"  
          Console.WriteLine($"String: '{s3.Format}'")
          Console.WriteLine($"Arguments: {s3.ArgumentCount}")
          Console.WriteLine($"Result string: {s3}")
       End Sub
    End Module
    ' The example displays the following output:
    '       String: 'Hello, {0}!'
    '       Arguments: 1
    '       Result string: Hello, Bartholomew!
    
    

另请参阅See also