【发布时间】:2020-03-31 09:29:47
【问题描述】:
如果能帮助我理解为什么以下 C# 代码不起作用,我将不胜感激。
//string[] array = new string[] { "a", "b", "c", "d" }; // this array works
var array = new [] {
new DateTime(2000, 1, 1),
new DateTime(2010, 12, 31)
};
var format = "{0:MMM}{1:MMM}";
Console.WriteLine(string.Format(format, array)); // compiles, but crashes at runtime
它编译没有问题,但在执行时崩溃并出现以下错误:
运行时异常(第 15 行):索引(从零开始)必须大于或等于零且小于参数列表的大小。
堆栈跟踪:[System.FormatException:索引(从零开始)必须大于或等于零且小于参数列表的大小。] 在 System.Text.StringBuilder.AppendFormatHelper(IFormatProvider 提供程序,字符串格式,ParamsArray args) 在 System.String.FormatHelper(IFormatProvider 提供程序,字符串格式,ParamsArray args) 在 System.String.Format(字符串格式,对象 arg0) 在 Program.Main() :第 15 行
我希望 the String.Format overload that accepts an object array 可以像使用字符串数组一样使用 DateTime 数组,但我是不是误会了什么?
【问题讨论】:
-
这行不通,因为它会将数组视为第 0 项,并且不会有第 1 项,因此出现异常。您需要更改代码以单独传递项目:
string.Format(format, date1, date2) -
一点小意思,
Console.WriteLine里面不用调用string.Format,直接用Console.WriteLine(format, array);就行了
标签: c# arrays datetime string-formatting