string.format()的使用
通常,我们使用string.format()来格式化字符串,例如:
string name="薄心之心";
string friendname="Tom";
string result=string.format("my name is {0},{1} is my best friend.",name,friendname);
$的使用
上面的代码我们也可以使用$来完成:
string name="薄心之心";
string friendname="Tom";
string result=$"my name is {name},{friendname} is my best friend.";
运行代码,我们会发现两者结果是一样的。
此外,$方式{}中的变量也可以是表达式,如:
int count=10;
int price=20;
string result=$"my cost is {count*price}";
string.format()和$有什么区别和联系呢?
(1) string.format()和$的结果是一样的,$的出现就是为了替代string.format()。
(2)$符号是C#6.0之后才出现的新特性,在之前的版本是没有这个功能的。
本文详细介绍了C#中$符号与string.format()的使用方法及区别,展示了如何利用$符号进行字符串格式化,包括变量和表达式的直接插入,并对比了其与string.format()的功能和适用场景。

16万+

被折叠的 条评论
为什么被折叠?



