C# 字符串格式的FormatException
我试图学习String.Format,但它一直抛出FormatException 有人能指出我的错误吗C# 字符串格式的FormatException,c#,C#,我试图学习String.Format,但它一直抛出FormatException 有人能指出我的错误吗 static void Main(string[] args) { var d = new DateTime(2016,5,10); var p = "Trumph"; Console.WriteLine(String.Format("Mr. {1} will be elected as president on {2}", p, d)); Console.R
static void Main(string[] args)
{
var d = new DateTime(2016,5,10);
var p = "Trumph";
Console.WriteLine(String.Format("Mr. {1} will be elected as president on {2}", p, d));
Console.ReadKey();
}
格式字符串中的索引是基于0的
Console.WriteLine(String.Format("Mr. {1} will be elected as president on {2}", p, d));
因此,您试图访问第二个和第三个格式参数(调用格式的第三个和第四个参数)
但您只指定了两个参数。因此,将格式字符串更改为:
Console.WriteLine(String.Format("Mr. {0} will be elected as president on {1}", p, d));
它应该会起作用
请注意,他们给了我们C#6,所以现在您可以这样做:
Console.WriteLine($"Mr. {p} will be elected as president on {d}");
格式字符串中的索引是基于0的
Console.WriteLine(String.Format("Mr. {1} will be elected as president on {2}", p, d));
因此,您试图访问第二个和第三个格式参数(调用格式的第三个和第四个参数)
但您只指定了两个参数。因此,将格式字符串更改为:
Console.WriteLine(String.Format("Mr. {0} will be elected as president on {1}", p, d));
它应该会起作用
请注意,他们给了我们C#6,所以现在您可以这样做:
Console.WriteLine($"Mr. {p} will be elected as president on {d}");
看看
看看你需要使用{0}
和{1}
你需要使用{0}
和{1}