我需要调用以下函数:
static string GetValueOrDefault(object[] values, int index)
{
if (values == null)
return string.Empty;
if (index >= values.Length)
return string.Empty;
return values[index] != null ? values[index].ToString() : string.Empty;
}
当我使用字符串数组 (ReferenceType) 调用 GetValueOrDefault 时,它起作用了:
GetValueOrDefault(new[] {"foo", "bar"}, 0);
当我用一个 int (ValueType) 数组调用 GetValueOrDefault 时,它不起作用:
GetValueOrDefault(new[] {1, 2}, 0);
编译器错误是:
The best overloaded method match for MyNamespace.GetValueOrDefault(object[], int)' has some invalid arguments
所以我的问题是:为什么这不能编译为 reference types and value type derive from object ?
我知道我可以使用泛型解决这个问题,但我想了解这个错误
static string GetValueOrDefault<T>(T[] values, int index)
{...}
提前致谢
最佳答案
引用类型的数组是协变的,这意味着:一个 string[]
可以被视为一个 object[]
(尽管问题是如果你试图把一个非字符串,它将抛出
)。但是,值类型的数组不是协变的,因此 int[]
不能被视为 对象[]
。 new[] {1,2}
是一个 int[]
。
IIRC 这样做主要是为了与 java 相似。 .NET 4.0 中的协方差更加简洁。
关于c# - ReferenceType 和 ValueType 的数组是对象数组的无效参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14583175/