我正在努力了解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();
}发布于 2016-03-30 11:33:56
格式字符串中的索引是基于0的.
Console.WriteLine(String.Format("Mr. {1} will be elected as president on {2}", p, d));因此,您正在尝试访问第二个和第三个格式参数( Format调用的第三个和第四个参数)。
但你只指定了两个参数。因此,将格式字符串更改为:
Console.WriteLine(String.Format("Mr. {0} will be elected as president on {1}", p, d));而且它应该能工作。
注意,他们给了我们https://learn.microsoft.com/de-de/dotnet/csharp/language-reference/tokens/interpolated和C# 6,所以现在您可以这样做了:
Console.WriteLine($"Mr. {p} will be elected as president on {d}");发布于 2016-03-30 11:34:33
Console.WriteLine(String.Format("Mr. {0} will be elected as president on {1}", p, d));看看C# string.Format方法
https://stackoverflow.com/questions/36307549
复制相似问题