IEnumerable<T>,IComparable<T>还有一些现在是类型变体的。IList<T>,ICollection<T>而许多其他人不是。为什么?
3 回答
11
.NET Framework 4.0 引入了安全协/逆变。IList<T>并且ICollection<T>have Tboth in input 和 output locations 而IEnumerable<T>has T only in output locations并且IComparable<T>has T only in input locations .
假设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
}
于 2009-05-31T19:16:41.063 回答
2
另请参阅:C# 4.0 协方差不能做什么
于 2009-05-31T21:28:17.787 回答
1
Anders Hejlseberg 在他的演讲“C# 的未来”中有一个简短但富有启发性的讨论,描述了协变/逆变。他关于协变和逆变的讨论从演讲开始的 50 分 17 秒开始。
于 2009-05-31T19:22:23.783 回答