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

原文地址:https://www.cnblogs.com/linmilove/p/10358640.html