我的"{0}"占位符不起作用。有没有办法修复它们


using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hi! What is your name?");
string name = Console.ReadLine();
Console.WriteLine("Hi {0} how are you? <Please write 'Good' or 'Bad'>", name);
string howAre = Console.ReadLine();
if (howAre == "Good")
{
Console.WriteLine("Excellent!");
Console.WriteLine("<Press Any Key To Continue>");
Console.ReadKey();
}
else if (howAre == "Bad")
{
Console.WriteLine("Don't {0} worry everyone always had a bad day :) " + name);
Console.WriteLine("<Press Any Key To Continue>");
Console.ReadKey();
}
else
{ 
Console.WriteLine("<Please write 'Good' or 'Bad'> ");
Console.WriteLine("<Press Any Key To Return>");
Console.ReadKey();
return;
}
}     
}
}

您需要更改行

Console.WriteLine("Don't {0} worry everyone always had a bad day :) " + name)

Console.WriteLine("Don't {0} worry everyone always had a bad day :) ", name)

在 C#6 及更高版本中,您可以使用字符串插值,这更具可读性和经济性:

Console.WriteLine($"Don't worry {name} everyone always had a bad day :)");

您需要更改此行:

Console.WriteLine("Don't {0} worry everyone always had a bad day :) " + name);

对此:

Console.WriteLine("Don't {0} worry everyone always had a bad day :) ", name);

为什么?

因为您使用+符号,而这只是打印Console.writeline后面的string name

如果将其更改为, name它将在{0}的位置打印出您的string name

只需在另一种方式上添加一些输入,您就可以在没有{0}的情况下执行此操作,这是使用字符串插值:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

例:

Console.WriteLine($"Don't {name} worry everyone always had a bad day");

最新更新