Unable to pass IEnumerable<Triangle> into a function that is looking for IEnumerable<IShape>
I have a collection of objects:
IE开发者_如何学Pythonnumerable<Triangle>
These objects support an interface IShape
but i am getting an error trying to pass this into a function that is asking for:
IEnumerable<IShape>
- Why can't I pass this in?
- Is there any workaround to convert one to the other to get this to work?
In .NET 4, this should be supported, as IEnumerable<T>
is declared to be covariant, i.e. the declaration is really IEnumerable<out T>
. In .NET 3.5, that is not the case, and you would need to use a workaround such as
triangles.Cast<IShape>()
(It's worth noting this was a language feature evolution as well; that is, if you somehow were able to use C# 3 with .NET 4, it would still not work, because support for co- and contravariance was not added to C# until version 4 of the language.)
An excellent explanation of co- and contravariance can be found in Jon Skeet's C# in Depth, section 13.3.
It's simple:
IEnumerable<Triangle>
does not inherit from and is not assignable to IEnumerable<IShape>
*
There is no relationship of that kind between the two types. It sounds like you really want a function more like this:
void MyFunction<T>(IEnumerable<T> items) where T : IShape
That says, "give me a function that accepts any IEnumerable<T>
where the T inherits from IShape". Alternatively, you could use the .Cast<T>()
extension method (it's surprisingly performant).
* On your version of the .Net Framework
精彩评论