Is placeholders necessary on c# when printing variables
在C++中,当你定义一个变量并想打印它时,你可以这样做。
1 | cout <<"Your varibales is" << var1 << endl; |
但为什么在C中,你需要一个占位符?
1 | Console.WriteLine("The answer is {0}" , answer); |
因为我在没有
如果变量必须是字符串,或者您必须使用
1 | Console.WriteLine("The answer is" + answer); // if answer is string |
让EDOCX1[1]成为一个日期时间对象,并且您只想打印格式为"dd-mmm-yyyy"的日期,然后您可以这样使用:
1 | Console.WriteLine("The answer is" + answer.ToString("dd-MMM-yyyy")); // if answer is not string |
占位符仅用于字符串格式:在内部,
1 2 | Console.Write("The answer is"); Console.WriteLine(answer); |
例如,或多或少等价于您在C++程序中所做的,因为语句:
1 | cout <<"Your varibales is" << var1 << endl; |
基本上可以归结为:
1 2 3 | cout2 = cout <<"Your varibales is"; cout3 = cout2 << var1; cout3 << endl; |
在
因为这就是
除了这些其他答案外,还可以使用字符串插值:
1 | Console.WriteLine($"The answer is {answer}"); |
当你尝试
1 | Console.WriteLine("The answer is" , answer); //without placeholder |
这不会给您带来错误,但不会打印
让我们举个例子来理解在哪里使用什么。假设在输出中有许多变量要显示。您可以使用占位符以便阅读。如
1 2 3 4 | string fname ="Mohit"; string lname ="Shrivastava"; string myAddr ="Some Place"; string Designation ="Some Desig"; |
现在让我们说,我们想在输出上显示一些字符串,就像
Hey!!
Mohit whose last name would beShrivastava is currently living atSome Place and he is working asSome Desig with so n so company.
因此,我们中的许多人可能会提出一种方法。
1 | 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."); |
在这种情况下,占位符对于更好的可读性起着至关重要的作用,例如
1 | 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字符串插值,您也可以像
1 | 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."); |