IEnumerable<T>
, IComparable<T>
and a few more are now type-variant. IList<T>
, ICollection<T>
and many others aren't. Why?
IEnumerable
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
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
}
#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秒。
#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
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秒。