派生列表到基本 IEnumerable

San*_*ero 3 c# ienumerable .net-2.0

我有以下在 .NET Framework 版本 4.0 及更高版本中编译的代码:

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> { }
Run Code Online (Sandbox Code Playgroud)

但在 4.0 以下的 .NET Framework 中,我在以下行中收到编译错误:

IEnumerable<MyBase> bases = deriveds;
Run Code Online (Sandbox Code Playgroud)

无法将类型“System.Collections.Generic.IList<T>”隐式转换为“System.Collections.Generic.IEnumerable”。存在显式转换(您是否缺少强制转换?)

问题是 .NET 4.0 对此进行了哪些更改(或引入)?
有这方面的文档吗?

Kev*_*tch 5

在 .Net 4.0 中,IEnumerable<T>接口更改为:

public interface IEnumerable<T>

public interface IEnumerable<out T>

请注意,单词 out 已添加到泛型类型参数中。这意味着泛型参数是协变的,这意味着您可以传入更派生的类型。

协方差使您能够使用比最初指定的派生类型更多的类型。您可以将 IEnumerable 的实例(在 Visual Basic 中为 IEnumerable(Of Derived))分配给 IEnumerable 类型的变量

请参阅msdn了解更多信息