Return an inherited type from a method

后端 未结 1 1135
忘了有多久
忘了有多久 2021-01-25 08:33

Suppose I have the following classes defined:

Public Class BaseClass
    ...
End Class

Public Class DerivedClass
    Inherits BaseClass

   ... Extra Fields, me         


        
1条回答
  •  温柔的废话
    2021-01-25 08:58

    Have a look at this:

    http://msdn.microsoft.com/en-us/library/dd799517(v=vs.110).aspx

    Understanding Covariance and Contravariance will clear things up a bit :)

    • Covariance

    Enables you to use a more specific type than originally specified. You can assign an instance of IEnumerable (IEnumerable(Of Derived) in Visual Basic) to a variable of type IEnumerable.

    Example:

    IEnumerable d = new List();
    IEnumerable b = d;
    
    • Contravariance

    Enables you to use a more generic (less derived) type than originally specified. You can assign an instance of IEnumerable (IEnumerable(Of Base) in Visual Basic) to a variable of type IEnumerable.

    Example:

    Action b = (target) => { Console.WriteLine(target.GetType().Name); };
    Action d = b;
    d(new Derived());
    
    • Invariance

    Means that you can use only the type originally specified; so an invariant generic type parameter is neither covariant nor contravariant. You cannot assign an instance of IEnumerable (IEnumerable(Of Base) in Visual Basic) to a variable of type IEnumerable or vice versa.

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