差補字串 (Visual Basic 參考)

可用來建構字串。 字串插值類似包含「插入運算式」的範本字串。 字串插值會傳回一個字串,以將內含的插入運算式取代為運算式的字串表示。 Visual Basic 14 及更新版本提供此功能。

字串插值的引數比複合格式字串更容易了解。 例如,字串插值

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

包含兩個插入運算式 '{name}' 和 '{hours:hh}'。 對等的複合格式字串為:

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

字串插值的結構為:

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

其中:

  • field-width 是帶正負號的整數,表示欄位中的字元數。 如果是正數,則欄位會靠右對齊;如果是負數,則會靠左對齊。

  • format-string 是一個格式字串,適用於將格式化的物件類型。 例如,若為 DateTime 值,差補字串可能是標準日期與時間格式字串,例如 "D" 或 "d"。

重要

字串開頭的 $" 之間不能有空白字元。 這樣做會造成編譯器錯誤。

您可以在使用字串常值的任何位置使用字串插值。 每次執行含有字串插值的程式碼時,都會評估字串插值。 這可讓您分開定義和評估字串插值。

若要在字串插值中包含大括弧 ("{" 或 "}"),請使用雙大括弧 "{{" 或 "}}"。 如需詳細資料,請參閱隱含轉換一節。

當字串插值包含在字串插值中具有特殊意義的其他字元時 (例如引號 (")、冒號 (:) 或逗號 (,)),如果這些字元出現在常值文字中,則必須將它逸出;如果這些字元是包含在插入運算式中的語言項目,則必須加入以括號分隔的運算式。 下列範例會逸出引號,使該差補字串包含在結果字串中:

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.

隱含的轉換

有三個來自字串插值的隱含型別轉換:

  1. 將字串插值轉換成 String。 下列範例會傳回一個字串,其字串插值運算式已取代為運算式的字串表示。 例如:

    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>
    

    這是字串解譯的最終結果。 所有出現的雙大括弧 ("{{" 和 "}}") 都會轉換成單一大括弧。

  2. 將字串插值轉換成 IFormattable 變數,可讓您從單一 IFormattable 執行個體建立多個具有特定文化特性內容的結果字串。 若要加入個別文化特性的正確數值和日期格式等項目時,這樣做會很有用。 在您明確或隱含呼叫 ToString() 方法以格式化字串之前,所有出現的雙大括弧 ("{{" 和 "}}") 會保持為雙大括弧。 所有包含內插補點的運算式都會轉換成 {0} 與 {1} 等。

    下列範例使用反映來顯示成員,以及從字串插值建立之 IFormattable 變數的欄位和屬性值。 它也會將 IFormattable 變數傳遞給 Console.WriteLine(String) 方法。

    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>
    
    

    請注意,只能使用反映來檢查字串插值。 如果將它傳遞至字串格式化方法 (例如 WriteLine(String)),則會解析其格式項目並傳回結果字串。

  3. 將差補字串轉換成 FormattableString 變數,代表複合格式字串。 檢查複合格式字串及其如何轉譯為結果字串有助於在建立查詢時,防止插入式攻擊。 FormattableString 也包括:

    在您格式化之前,所有出現的雙大括號 ("{{" 與 "}}") 都會保持為雙大括號。 所有包含內插補點的運算式都會轉換成 {0} 與 {1} 等。

    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!
    
    

另請參閱