基于IEnumerable的派生列表 [英] Derived List to Base IEnumerable
问题描述
我具有在.NET Framework 4.0及更高版本中编译的以下代码:
I have the following code that compiles in .NET Framework version 4.0 and above:
public abstract class MyBase { }
public class MyDerived : MyBase { }
public abstract class MyBaseCollection<T> : IList<T> where T : MyBase
{
protected readonly IList<T> deriveds = new List<T>();
public void Test()
{
// This line works in .NET versions 4.0 and above, but not in versions below.
IEnumerable<MyBase> bases = deriveds;
}
#region IList members with NotImplementedException
// ...
#endregion
}
public class MyDerivedCollection : MyBaseCollection<MyDerived> { }
但是在低于4.0的.NET Framework中,我在下一行得到了编译错误:
But in .NET Framework below 4.0 I get a compile error on the following line:
IEnumerable<MyBase> bases = deriveds;
无法隐式转换类型'System.Collections.Generic.IList< T>'到"System.Collections.Generic.IEnumerable".存在显式转换(您是否缺少演员表?)
Cannot implicitly convert type 'System.Collections.Generic.IList<T>' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)
问题是在.NET 4.0中对此进行了哪些更改(或已引入)?
是否有任何相关文档?
Question is what has changed (or was introduced) in .NET 4.0 regarding this?
Is there any documentation about this?
推荐答案
在.Net 4.0中,IEnumerable<T>
接口已从以下位置更改:
In .Net 4.0 the IEnumerable<T>
interface was changed from:
public interface IEnumerable<T>
public interface IEnumerable<T>
至
public interface IEnumerable<out T>
To
public interface IEnumerable<out T>
请注意,单词out已添加到泛型类型参数中.这意味着泛型参数是协变的,这意味着您可以传递更多派生的类型.
Notice that the word out has been added to the generic type parameter. This means that the generic parameter is co-variant which means you can pass in a more derived type.
协方差使您可以使用比原始类型更多的派生类型 指定的.您可以分配IEnumerable的实例 (在Visual Basic中为IEnumerable(Of Derived))为类型的变量 IEnumerable
Covariance Enables you to use a more derived type than originally specified. You can assign an instance of IEnumerable (IEnumerable(Of Derived) in Visual Basic) to a variable of type IEnumerable
有关更多信息,请参见 msdn 信息
See msdn for more information
这篇关于基于IEnumerable的派生列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!