C# 中的字符串內插


 

$ 特殊字符將字符串文本標識為內插字符串。 內插字符串是可能包含內插表達式的字符串文本。 將內插字符串解析為結果字符串時,帶有內插表達式的項會替換為表達式結果的字符串表示形式。 此功能在 C# 6 及該語言的更高版本中可用。
與使用字符串復合格式設置功能創建格式化字符串相比,字符串內插提供的語法更具可讀性,且更加方便。 下面的示例使用了這兩種功能生成同樣的輸出結果:

string name = "Mark";
var date = DateTime.Now;

// Composite formatting:
Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);
// String interpolation:
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
// Both calls produce the same output that is similar to:
// Hello, Mark! Today is Wednesday, it's 19:40 now.

內插字符串的結構
若要將字符串標識為內插字符串,可在該字符串前面加上 $ 符號。 字符串文本開頭的 $ 和 " 之間不能有任何空格。 如果有空格,會導致編譯時錯誤。
具備內插表達式的項的結構如下所示:

{<interpolatedExpression>[,<alignment>][:<formatString>]}
括號中的元素是可選的。 下表說明了每個元素:
interpolatedExpression 生成需要設置格式的結果的表達式。 null 結果的字符串表示形式為 String.Empty。
alignment 常數表達式,它的值定義內插表達式結果的字符串表示形式中的最小字符數。 如果值為正,則字符串表示形式為右對齊;如果值為負,則為左對齊。 有關詳細信息,請參閱對齊組件。
formatString 受表達式結果類型支持的格式字符串。 有關更多信息,請參閱格式字符串組件。
以下示例使用上述可選的格式設置組件:

Console.WriteLine($"|{"Left",-7}|{"Right",7}|");

const int FieldWidthRightAligned = 20;
Console.WriteLine($"{Math.PI,FieldWidthRightAligned} - default formatting of the pi number");
Console.WriteLine($"{Math.PI,FieldWidthRightAligned:F3} - display only three decimal digits of the pi number");
// Expected output is:
// |Left   |  Right|
//     3.14159265358979 - default formatting of the pi number
//                3.142 - display only three decimal digits of the pi number    

特殊字符
要在內插字符串生成的文本中包含大括號 "{" 或 "}",請使用兩個大括號,即 "{{" 或 "}}"。 有關詳細信息,請參閱轉義大括號。
因為冒號 (":") 在內插表達式項中具有特殊含義,為了在內插表達式中使用條件運算符,請將表達式放在括號內。
以下示例演示如何將大括號含入結果字符串中,以及如何在內插表達式中使用條件運算符:

string name = "Horace";
int age = 34;
Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
// Expected output is:
// He asked, "Is your name Horace?", but didn't wait for a reply :-{
// Horace is 34 years old.

逐字內插字符串以 $ 字符開頭,后跟 @ 字符。 有關逐字字符串的詳細信息,請參閱字符串和逐字標識符主題。

隱式轉換和指定 IFormatProvider 實現
內插字符串有 3 種隱式轉換:
將內插字符串轉換為 String 實例,該類例是內插字符串的解析結果,其中內插表達式項被替換為結果的格式設置正確的字符串表示形式。 此類轉換使用當前區域性。
將內插字符串轉換為表示復合格式字符串的 FormattableString 實例,同時也將表達式結果格式化。 這允許通過單個 FormattableString 實例創建多個包含區域性特定內容的結果字符串。 要執行此操作,請調用以下方法之一:
ToString() 重載,生成 CurrentCulture 的結果字符串。
Invariant 方法,生成 InvariantCulture 的結果字符串。
ToString(IFormatProvider) 方法,生成特定區域性的結果字符串。
你還可使用 ToString(IFormatProvider) 方法,以提供支持自定義格式設置的 IFormatProvider 接口的用戶定義實現。 有關詳細信息,請參見使用 ICustomFormatter 進行自定義格式設置。
將內插字符串轉換為 IFormattable 實例,使用此實例也可通過單個 IFormattable 實例創建多個包含區域性特定內容的結果字符串。
以下示例通過隱式轉換為 FormattableString 來創建特定於區域性的結果字符串:

double speedOfLight = 299792.458;
FormattableString message = $"The speed of light is {speedOfLight:N3} km/s.";

System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("nl-NL");
string messageInCurrentCulture = message.ToString();

var specificCulture = System.Globalization.CultureInfo.GetCultureInfo("en-IN");
string messageInSpecificCulture = message.ToString(specificCulture);

string messageInInvariantCulture = FormattableString.Invariant(message);

Console.WriteLine($"{System.Globalization.CultureInfo.CurrentCulture,-10} {messageInCurrentCulture}");
Console.WriteLine($"{specificCulture,-10} {messageInSpecificCulture}");
Console.WriteLine($"{"Invariant",-10} {messageInInvariantCulture}");
// Expected output is:
// nl-NL      The speed of light is 299.792,458 km/s.
// en-IN      The speed of light is 2,99,792.458 km/s.
// Invariant  The speed of light is 299,792.458 km/s.

本文轉自:https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/tokens/interpolated


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM