打印变量时 c# 上是否需要占位符

Is placeholders necessary on c# when printing variables

在 C++ 中,当您定义了一个变量并且想要打印它时,您可以这样做

cout << "Your varibales is" << var1 << endl;

但为什么在 C# 中需要占位符才能这样做?

Console.WriteLine("The answer is {0}" , answer);

因为打印没有 placeholder 的答案时出错。 我在网上搜索过,但没有提供我需要的信息..

在变量必须是字符串的条件下,您不必像这样使用连接,否则您必须使用 .ToString() 进行转换并格式化对象:

Console.WriteLine("The answer is " + answer); // if answer is string

answer 成为一个 DateTime 对象,并且您只想从格式为 "dd-MMM-yyyy" 的日期打印日期,那么您可以这样使用:

Console.WriteLine("The answer is " + answer.ToString("dd-MMM-yyyy")); // if answer is not string

因为这就是 String.Format 的工作方式。 Console.WriteLine 在内部使用 String.Format。你可以写类似 Console.WriteLine("The answer is " + answer); 的东西。

占位符只用于字符串格式化:在内部WriteLine方法会调用String.Format方法,但是你可以自己格式化,或者使用多个 Console.Write 语句:

Console.Write("The answer is ");
Console.WriteLine(answer);

For instance 或多或少等同于你在 C++ 程序中所做的,因为语句:

cout << "Your varibales is" << var1 << endl;

基本上可以归结为:

cout2 = cout << "Your varibales is";
cout3 = cout2 << var1;
cout3 << endl;
cout 上的

<< 或多或少等同于在 Console 上调用 Write<< 只是 returns 控制台对象,这样就可以使用 chaining.

当你尝试时

Console.WriteLine("The answer is " , answer); //without placeholder

这不会给您错误,但不会打印 answer 并且控制台输出将是 The answer is,因为您还没有告诉将变量 answer 放在哪里。因此,如果您想打印答案,您可以按照其他 post 的建议使用 + 进行连接,或者您必须使用占位符

让我们举个例子来了解在哪里使用什么。假设您有许多变量要显示在输出中。您可以使用占位符以便于阅读。比如

string fname = "Mohit";
string lname = "Shrivastava";
string myAddr = "Some Place";
string Designation = "Some Desig";

现在假设我们想在输出中显示一些字符串,类似于

Hey!! Mohit whose last name would be Shrivastava is currently living at Some Place and he is working as Some Desig with so n so company.

因此,我们许多人建议的一种方法

Console.WriteLine("Hey!! " + fname + " whose last name would be " + lname + " is currently living at " + myAddr + " and he is working as " + Designation + " with so n so company.");

在这种情况下,占位符对于提高可读性起着至关重要的作用,例如

Console.WriteLine("Hey!! {0} whose last name would be {1} is currently living at {2} and he is working as {3} with so n so company.",fname,lname,myAddr,Designation);

使用 C#6.0 String Interpolation 你也可以像

这样高效的方式做到这一点
Console.WriteLine($"Hey!! {fname} whose last name would be {lname} is currently living at {myAddr} and he is working as {Designation} with so n so company.");

除了这些其他答案外,您还可以使用字符串插值

Console.WriteLine($"The answer is {answer}");