Passing a generic collection of objects to a method that requires a collection of the base type

后端 未结 2 999
情深已故
情深已故 2020-12-21 02:18

Say I have a method that is expecting a generic collection parameter of a base type, see Test.MethodA(IEnumerable(BaseClass) listA) below. How come when I p

相关标签:
2条回答
  • 2020-12-21 02:51

    In the general case (i.e. for collections that are modifiable), it is NOT the case that "a collection of DerivedClass has all the same properties as a collection of BaseClass": into a collection of Fruit you can insert Banana, Apple and Pear -- in a collection of Orange, you can't, so, you see, it doesn't have the same properties (under modification).

    IEnumerable is a different case, since it's NOT modifiable, as as @Jon says this excessive restriction has been removed for that special case in 4.0.

    0 讨论(0)
  • 2020-12-21 02:52

    Cast<>() is the best way to solve it at the moment. Your original version would work fine in C# 4.0 / .NET 4.0 though, where IEnumerable<T> is covariant in T.

    (I've just verified it compiles under .NET 4.0 beta 1.)

    Until .NET 4.0 and C# 4 come out, generics are invariant - IEnumerable<object> and IEnumerable<string> are effectively unrelated interfaces. Even in .NET 4.0, you wouldn't be able to do this with List<T> as the parameter type - only interfaces and delegates will be variant, and even then only when the type parameter is only used in appropriate positions (output positions for covariance, input positions for contravariance).

    To learn more about variance in C# 4, read Eric Lippert's excellent series of blog posts about it.

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