你一直在使用 +
从变量和常量字符串构建字符串。 但还有一种更好的方法。 你可以在 {
和 }
字符之间放置一个变量,以告诉 C# 将该文本替换为此变量的值。
这称为字符串内插。
如果在字符串的左引号前添加 $
,则可以在大括号之间的字符串内包括变量,如 aFriend
。 试一试:
C#复制
Console.WriteLine($"Hello {aFriend}");
再次选择“运行”,看看结果如何。 消息应该是“Hello Maira”,而不是“Hello {aFriend}”。
再例如
int i = 3;
Console.WriteLine($"Hello {i}");
Console.WriteLine("Hello {i}");
运行结果
注意:$符号
之前一直没有正确识别,主要是没有注意到$符号
其他一些信息
接下来,将进一步探索。
不仅限于使用大括号之间的单个变量。 试运行以下代码:
string firstFriend = "Maria";
string secondFriend = "Sage";
Console.WriteLine($"My friends are {firstFriend} and {secondFriend}");
当使用字符串进行更多探索时,你会发现字符串不仅仅是字母集合。 你可以使用 Length
得出字符串的长度。 Length
是字符串属性,可返回字符串中的字符数。 在交互式窗口的底部,添加以下代码:
Console.WriteLine($"The name {firstFriend} has {firstFriend.Length} letters.");
Console.WriteLine($"The name {secondFriend} has {secondFriend.Length} letters.");
输出结果
特此记录
anlog
2022年9月9日