IEnumerable<T>, IComparable<T> 还有一些现在是类型变体。 IList<T>, ICollection<T> 而其他许多人则不然。为什么?

有帮助吗?

解决方案

的.NET Framework 4.0引入的安全 CO /禁忌方差。 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
}

其他提示

安德斯Hejlseberg具有短暂,但照明讨论描述在谈话CO /逆变,“C#的未来”。他对协方差和逆变讨论开始在50分17秒到演示。

http://channel9.msdn.com/pdc2008/TL16/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top