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

后端 未结 2 1007
情深已故
情深已故 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.

提交回复
热议问题