在.NET Framework 4.0中键入差异

时间:2021-12-04 16:05:49

IEnumerable<T>, IComparable<T> and a few more are now type-variant. IList<T>, ICollection<T> and many others aren't. Why?

IEnumerable ,IComparable 和其他一些现在是type-variant。 IList ,ICollection 和其他许多不是。为什么?

3 个解决方案

#1


.NET Framework 4.0 introduces safe co/contra-variance. IList<T> and ICollection<T> have T both in input and output positions while IEnumerable<T> has T only in output positions and IComparable<T> has T only in input positions.

.NET Framework 4.0引入了安全协同/反差。 IList 和ICollection 在输入和输出位置都有T,而IEnumerable 仅在输出位置具有T而IComparable 仅在输入位置具有T.

Assume IList<T> supported type variance:

假设IList 支持的类型方差:

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
}

#2


See also: What C# 4.0 covariance doesn't do

另请参阅:C#4.0协方差不起作用

#3


Anders Hejlseberg has a brief, but illuminating discussion that describes co/contravariance in his talk, "The Future of C#." His discussion on covariance and contravariance starts at 50 minutes and 17 seconds into the presentation.

Anders Hejlseberg有一个简短但有启发性的讨论,描述了他的演讲中的共同/逆转,“C#的未来”。他对协方差和逆变的讨论始于演讲的50分17秒。

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

#1


.NET Framework 4.0 introduces safe co/contra-variance. IList<T> and ICollection<T> have T both in input and output positions while IEnumerable<T> has T only in output positions and IComparable<T> has T only in input positions.

.NET Framework 4.0引入了安全协同/反差。 IList 和ICollection 在输入和输出位置都有T,而IEnumerable 仅在输出位置具有T而IComparable 仅在输入位置具有T.

Assume IList<T> supported type variance:

假设IList 支持的类型方差:

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
}

#2


See also: What C# 4.0 covariance doesn't do

另请参阅:C#4.0协方差不起作用

#3


Anders Hejlseberg has a brief, but illuminating discussion that describes co/contravariance in his talk, "The Future of C#." His discussion on covariance and contravariance starts at 50 minutes and 17 seconds into the presentation.

Anders Hejlseberg有一个简短但有启发性的讨论,描述了他的演讲中的共同/逆转,“C#的未来”。他对协方差和逆变的讨论始于演讲的50分17秒。

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