派生列表到基础 IEnumerable

Derived List to Base IEnumerable

我有以下在 .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> { }

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

IEnumerable<MyBase> bases = deriveds;

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 对此有何改变(或引入)?
有没有关于这个的文档?

是关于集合的协变和逆变。查看以下内容 link 以获取更多信息。

Starting with the .NET Framework 4, several generic interfaces have covariant type parameters; for example: IEnumerable, IEnumerator, IQueryable, and IGrouping. All the type parameters of these interfaces are covariant, so the type parameters are used only for the return types of the members.

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

public interface IEnumerable<T>

public interface IEnumerable<out T>

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

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