从generic []参数

时间:2016-08-09 14:42:49

标签: c# .net generics casting

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

示例:

// 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.Format接受一个object []作为第二个参数时会发生这种情况吗?谢谢!

1 个答案:

答案 0 :(得分:2)

  

为什么当String.Format接受object[]作为第二个参数时会发生这种情况?

这正是它发生的原因 - T[]不一定是object[],因此除非T在特定调用中恰好是object,否则投射会失败。

您可以通过在通话中转换为object[]来解决此问题,例如:

err_msg += String.Format(ErrorMessages.Index[errorCode], paramArgs.Cast<object>().ToArray());