【问题标题】:In C# how do you use placeholders in Console.WriteLine()? [duplicate]在 C# 中,如何在 Console.WriteLine() 中使用占位符? [复制]
【发布时间】:2015-08-22 07:22:15
【问题描述】:

我是否在下面的代码中正确使用了{0}{1} 作为名称变量和年龄变量? {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(第一块的第二行)是最佳实践。

标签: c#


【解决方案1】:

是的,它们被称为占位符。再说一次,当你像下面这样说而不是串联时,它看起来不是更易读吗

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

【讨论】:

    【解决方案2】:

    {0} 和 {1} 称为占位符或格式项。

    至于第二题检查String output: format or concat in C#?

    【讨论】:

      【解决方案3】:

      使用 C# 6,您现在可以使用混合解决方案:

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

      这被称为string interpolation

      【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 2011-10-25
      • 1970-01-01
      • 2018-10-13
      • 2014-05-21
      • 1970-01-01
      • 2022-11-07
      • 1970-01-01
      相关资源
      最近更新 更多