I have generic container class I'm using that I'm trying to write a OfType routine for. However the types I'm passing in are also generics. Here's an example:
Entities.OfType<Foo<Bar>>()
and my function definition:
public IEnumerable T OfType<T>()
{
foreach (var e in Values)
if (e is T)
yield return (T)e;
}
If Entities are defined as a collection of Foo<Base>
I get an error Foo<Bar>
does not inherit from Foo<Base>
. However Bar does inherit from Base.
Is the开发者_如何学编程re a way around this limitation?
Note that even though Bar
inherits from Base
- Foo<Bar>
and Foo<Base>
are two completely different generic types not related through inheritance.
Bar
and Base
in this case are type parameters and C#4.0 supports covariance/contravariance for generic interfaces which may help you to solve the problem.
Your code will work in C#4.0 if Foo
is an interface declared as following:
interface IFoo<in T> { /* methods, etc. */ }
Note that no method in IFoo
may return T
.
You'll be able to assign IFoo<Base>
object to a variable of type IFoo<Bar>
where Bar
inherits from Base
. This is an example of contravariance.
C# Generics are not covariant. A Foo<Bar>
is not assignment-compatible with Foo<Base>
精彩评论