在C#中,如何在Console.WriteLine()中使用占位符?

4

以下代码中,我是否正确地使用了{0}{1}来表示变量name和age?这些{0}{1}被称为“占位符”吗?在将变量加入到Console.Writeline()中时,使用+连接还是占位符系统更好呢?

Console.WriteLine("Hi " + nameInput + ", you are " + ageInteger + " years old.");
Console.WriteLine("Hi {0}, you are {1} years old.", nameInput, ageInteger);

完整代码:

string nameInput;
string ageInputString;
int ageInteger;
Console.WriteLine("Enter your name");
nameInput = Console.ReadLine();
Console.WriteLine("Enter your age");
ageInputString = Console.ReadLine();
Int32.TryParse(ageInputString, out ageInteger);
Console.WriteLine("Hi " + nameInput + ", you are " + ageInteger + " years old.");
Console.WriteLine("Press Enter to quit.");
Console.ReadLine();

选项#2(第一个块中的第二行)将是最佳实践。 - abatishchev
3个回答

11

在C# 6中,你现在可以使用混合方案:

Console.WriteLine($"Hi {nameInput} you are {ageInteger} years old."); 

这被称为字符串插值


根据文档所述,应该优先选择这种方法,因为:字符串插值提供了比字符串复合格式化功能更易读和方便的语法来创建格式化字符串。 - Lucas
另外需要记住的是始终使用占位符并避免字符串插值 - malat

3
是的,它们被称为占位符。当你像下面这样说而不是连接时,它看起来更易读。
Console.WriteLine("Hi {0} you are  {1} years old.", nameInput, ageInteger); 

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接