开发者

How do I convert a IEnumerable<SubClass> to IEnumerable<ParentClass>

How do I go from (cast?, convert?开发者_开发技巧):

IEnumerable<Square>

to

IEnumerable<Shape>


If you're using anything lower than .NET 4.0, then you're going to have to use IEnumerable.Cast:

IEnumerable<Square> squares = new List<Square>();

// Fill the collection

IEnumerable<Shape> shapes = squares.Cast<Shape>();

.NET 4.0 introduces new Covariance and Contravariance features that allow you to make that cast directly:

IEnumerable<Square> squares = new List<Square>();
IEnumerable<Shape> shapes = (IEnumerable<Shape>)squares;


var shapes = squares.Cast<Shape>();


If you're using .NET 4.0, you don't have to.

From Covariance and Contravariance in Generics (emphasis added):

Polymorphism enables you to assign an instance of Derived to a variable of type Base. Similarly, because the type parameter of the IEnumerable(T) interface is covariant, you can assign an instance of IEnumerable<Derived> to a variable of type IEnumerable<Base>...

Since you're asking this question, I assume you're not using .NET 4.0 yet. But this might be a reason to upgrade, if you're able to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜