C#中的字符串差值

基本例子

创建了两个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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值