【问题标题】:Trouble using String.Format() with a DateTime array将 String.Format() 与 DateTime 数组一起使用时遇到问题
【发布时间】: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


【解决方案1】:

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)
};

它应该可以工作。

【讨论】:

  • 抱歉来晚了,但非常感谢你,Marc。这正是我所需要的。
【解决方案2】:

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

喜欢

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

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

【讨论】:

    猜你喜欢
    • 2013-03-27
    • 2013-03-20
    • 2021-07-15
    • 2013-06-19
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多