将 String.Format() 与 DateTime 数组一起使用时出现问题

Trouble using String.Format() with a DateTime array

如果能帮助我理解以下 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

它编译没有问题,但在执行时崩溃并出现以下错误:

Run-time exception (line 15): Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

Stack Trace: [System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.] at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args) at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args) at System.String.Format(String format, Object arg0) at Program.Main() :line 15

我预计 the String.Format overload that accepts an object array 会像处理字符串数组一样处理 DateTime 数组,但我是不是误会了什么?

一个DateTime[]不是一个object[];这不是数组方差的工作方式 - 所以:如果你将 DateTime[] 数组传递给 string.Format,它没有使用 Format(string, object[]) 重载 - 你 有效 使用将整个 DateTime[] 作为 单个 对象传递给 Format(string, object),因此从 Format 的角度来看,您只能使用令牌 0.

基本上,使用:

var array = new object[] {
       new DateTime(2000, 1, 1),
       new DateTime(2010, 12, 31)
};

它应该可以工作。

var format = "{0:MMM}{1:MMM}"; 需要为 string.Format() 提供三个参数 - 一个用于格式,两个参数用于值。

喜欢

string.Format(format, array[0], array[1])

另一种选择是将数组从 DateTime[] 更改为 object[] 数组