开发者

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

开发者 https://www.devze.com 2023-01-09 16:39 出处:网络
How do I go from (cast?, convert?开发者_开发技巧): IEnumerable<Square> to IEnumerable<Shape>

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

精彩评论

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