.net - .NET Framework 4.0中的类型差异

标签 .net generics types covariance contravariance

IEnumerable<T>IComparable<T>和其他一些现在是类型变量。 IList<T>ICollection<T>和其他很多不是。为什么?

最佳答案

.NET Framework 4.0引入了安全 co/contra-variance。 IList<T>ICollection<T>在输入和输出位置均具有T,而IEnumerable<T>仅在输出位置具有T,而IComparable<T>仅在输入位置具有T

假设IList<T>支持的类型差异:

static void FailingMethod(IList<object> list) {
    list[0] = 5;
}

static void Test() {
    var a = new List<string>();
    a[0] = "hello";
    FailingMethod(a); // if it was variant, this method call would be unsafe
}

关于.net - .NET Framework 4.0中的类型差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/932650/

相关文章:

c# - IDictionary<string, string> 与 Dictionary<string, string>

types - 在 swift 中检测对象是否恰好是特定类型而不是该类型的子类

.net - 步骤失败后,是否可以在 Visual Studio Team Services(以前是 VS Online)中重试 VS Test 构建步骤?

c# - 由于通用基类,不能使用多态性

c# - 以 3D 形式渲染点或平面

swift - 类型开关模式

curl - 为什么我不能将切片更改为 H512?

php - 在 PHP 数组中指定数据类型

c# - 如何使用Dockerfile覆盖ASP.NET Core连接字符串

c# - 如何使用 CsvHelper 从特定行读取标题?