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/