用來建構字串。 內插字串看起來像包含 插補表達式的範本字串。 插值字串會傳回一個字串,將其中包含的插值表達式以相應的字串形式替換。 這項功能適用於 Visual Basic 14 和更新版本。
插入字串的自變數比 複合格式字串更容易理解。 例如,下列插補字串包含兩個插補運算式, {name}
和 {hours:hh}
:
Console.WriteLine($"Name = {name}, hours = {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.
隱含轉換
內插字串有三個隱含類型轉換:
將插值字串轉換成 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>
這是字串解譯的最終結果。 所有出現的雙大括弧(“{{” 和 “}}”)都會轉換成單個大括弧。
將插入字串轉換成變數,可讓您從單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),其格式專案會解析並傳回結果字串。
將插入字串轉換成 FormattableString 代表複合格式字串的變數。 例如,檢查複合格式字串及其轉譯結果字串的方式,可協助您在建置查詢時防範插入式攻擊。 FormattableString也包括:
- ToString() 重載,用於產生 CurrentCulture 的結果字串。
- 產生 Invariant 字串的方法 InvariantCulture。
- ToString(IFormatProvider)產生指定文化特性之結果字串的方法。
所有出現的雙大括弧 (“{{” 和 “}}”) 都會保持為雙大括弧,直到您格式化為止。 所有包含的插補運算式都會轉換成 {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!
另請參閱
- System.IFormattable
- System.FormattableString
- Visual Basic 語言參考