c# - ReferenceType 和 ValueType 的数组是对象数组的无效参数

标签 c# arrays

我需要调用以下函数:

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/

相关文章:

c# - Couchbase Lite 数据库创建 C# .NET

在c中使用malloc创建数组

python - 当我有大量数组时检查重复数组

python追加到json对象中的数组

javascript 遍历数组

javascript - 使用 lodash groupBy 以正确的方式构建数组

c# - Azure Service Fabric 消息队列

c# - 如何检查我从文本框中输入的 "ID"在我的 MySql 表中不存在?

c# - 如何从excel导入documentDB中的批量数据?

c# - 查找c#中某个子字符串后面出现的第一个数字的索引