基本例子
创建了两个int变量:foo和bar。
int foo = 34;
int bar = 42;
string resultString = $"The foo is {foo}, and the bar is {bar}.";
Console.WriteLine(resultString);
输出:The foo is 34, and the bar is 42.
表达式
使用字符串插值,也可以计算花括号{}内的表达式。结果将插入字符串中的相应位置。例如,要计算foo和bar的最大值并插入它,Math.Max
在花括号内使用Math.Max
:
var foo = 34;
var bar = 42;
Console.WriteLine($"And the greater one is: { Math.Max(foo, bar) }");
输出:And the greater one is: 42
另一个例子,变量可以格式化为货币:
var foo = 34;
var bar = 42;
Console.WriteLine($"Foo formatted as a currency to 4 decimal places: {foo:c4}");
输出:Foo formatted as a currency to 4 decimal places: ¥34.0000
或者它们可以格式化为日期:
Console.WriteLine($"Today is: {DateTime.Today:dddd, MMMM dd - yyyy}");
输出:Today is: 星期四, 十月 24 - 2019
也可以在插值中评估带三元运算符语句。但是,这些必须用括号括起来,因为冒号用于表示格式,如下所示:
var foo = 34;
var bar = 42;
Console.WriteLine($"{(foo > bar ? "Foo is larger than bar!" : "Bar is larger than foo!")}");
输出:Bar is larger than foo!
条件表达式和格式说明符可以混合使用:
Console.WriteLine($"Environment: {(Environment.Is64BitProcess ? 64 : 32):00'-bit'} process");
输出:Environment: 64-bit process