String.Format中的FormatException

fab*_*net 0 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.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)

Ren*_*ogt 5

格式字符串中的索引从0开始。

Console.WriteLine(String.Format("Mr. {1} will be elected as president on {2}", p, d));
Run Code Online (Sandbox Code Playgroud)

因此,您尝试访问第二和第三格式参数(Format调用的第三和第四参数)。

但是您只指定了两个参数。因此,将格式字符串更改为:

Console.WriteLine(String.Format("Mr. {0} will be elected as president on {1}", p, d));
Run Code Online (Sandbox Code Playgroud)

它应该工作。


请注意,他们为我们提供了使用C#6进行字符串插值的功能,因此现在您可以执行以下操作:

Console.WriteLine($"Mr. {p} will be elected as president on {d}");
Run Code Online (Sandbox Code Playgroud)