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 typeIEnumerable<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.
精彩评论