字符串.当从泛型[]参数传递obj[]时,格式崩溃

本文关键字:格式 崩溃 obj 参数传递 泛型 字符串 | 更新日期: 2023-09-27 18:01:25

今天遇到了一个有趣的问题,我更改了一些错误生成方法,以接受泛型数组作为参数,而不是显式字符串[]。但是,当我试图将泛型参数数组传递给String时。稍后在方法中调用Format,它会使其崩溃,并尝试从String中访问数组。Format只返回集合中的一个元素:集合类型。

的例子:

// Just a small snippet of affected code
// Passing in 1 and a new string[] { "FIRST", "SECOND" }
public void SetErrorProperties(int errorCode, string[] paramArgs)
{
    Dictionary<int, string> ErrorMessages = new Dictionary<int, string>(){ {1, "TEST MESSAGE: {0} {1}"} };
    err_msg += String.Format(ErrorMessages.Index[errorCode], paramArgs);
    //works just fine, returns "TESTING MESSAGE: FIRST SECOND"  
}
public void SetErrorProperties<T>(int errorCode, T[] paramArgs)
{
    Dictionary<int, string> ErrorMessages = new Dictionary<int, string>(){ {1, "TEST MESSAGE: {0} {1}"} };
    err_msg += String.Format(ErrorMessages.Index[errorCode], paramArgs);
    // now this returns an error of Format Exception: Index (zero based) must be greater than or equal to zero and less than the size of the argument list
    // accessing array directly paramArgs[0] returns "FIRST" and paramArgs[1] returns "SECOND"
    // However, String.Format("{0}", paramArgs) returns "System.String[]" and String.Format ("{0} {1}", paramArgs) return the index exception
}

有谁知道为什么当String。格式接受对象[]作为第二个参数?谢谢!

字符串.当从泛型[]参数传递obj[]时,格式崩溃

为什么当String。Format接受object[]作为第二个参数?

这就是它发生的原因- T[]不一定是object[],所以除非T在特定调用中恰好是object,否则强制转换失败。

你可以通过在调用中转换为object[]来解决这个问题,像这样:
err_msg += String.Format(ErrorMessages.Index[errorCode], paramArgs.Cast<object>().ToArray());