Derived List to Base IEnumerable

前端 未结 2 1524
失恋的感觉
失恋的感觉 2021-01-24 15:51

I have the following code that compiles in .NET Framework version 4.0 and above:

public abstract class MyBase { }
public class MyDerived : MyBase { }

public abs         


        
相关标签:
2条回答
  • 2021-01-24 16:07

    It's about covariance and contravariance of collections. Check the following link to get more information.

    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.

    0 讨论(0)
  • 2021-01-24 16:29

    In .Net 4.0 the IEnumerable<T> interface was changed from:

    public interface IEnumerable<T>

    To public interface IEnumerable<out T>

    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.

    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

    See msdn for more information

    0 讨论(0)
提交回复
热议问题