C#中$的用法?(c#中@的用法)
文章来自AI问答。
在C#中,$符号用于字符串插值(String Interpolation)。字符串插值是C# 6.0引入的一种特性,它允许你在字符串中直接嵌入表达式,而不需要使用string.Format或字符串连接操作(如+或StringBuilder)。
基本用法
字符串插值的基本语法是在字符串前面加上$符号,然后在字符串中使用花括号{}包裹需要插入的表达式。例如:
string name = "Kimi";
int age = 5;
string message = #34;Hello, my name is {name} and I am {age} years old.";
Console.WriteLine(message);
输出:
Hello, my name is Kimi and I am 5 years old.
插入表达式
你可以在花括号中插入任何有效的C#表达式,包括变量、方法调用、运算符等。例如:
csharp复制
int a = 10;
int b = 20;
string result = #34;The sum of {a} and {b} is {a + b}.";
Console.WriteLine(result);
输出:
The sum of 10 and 20 is 30.
格式化
字符串插值还支持格式化,你可以在花括号中使用冒号:来指定格式化字符串。例如:
csharp复制
double price = 123.456;
string formattedPrice = #34;The price is {price:C2}.";
Console.WriteLine(formattedPrice);
输出:
The price is $123.46.
转义
如果需要在字符串中插入$符号本身,可以使用双$来表示一个$符号。例如:
csharp复制
string money = #34;I have $100.";
Console.WriteLine(money);
输出:
I have $100.
总结
字符串插值是C#中一种非常方便的字符串处理方式,它使得代码更加简洁、易读,并且减少了字符串拼接时可能出现的错误。