how to return an IList with members of an arbitrary type
I'm not sure this is even possible, but here goes: I have a class Zoo
which holds a dictionary of Animal Type -> List of Animals. e.g.
Cat Type -> {Cat1, Cat2}
Zebra Type -> {Zebra1, Zebra2}
Cat
and Zebra
are subclasses of Animal
. Now Zoo
has a method IList<Animal>
GetAnimalsOfType(Type type)
.
I'd like the return value to be of the type of the animal requested, so instead of getting an IList<Animal>
I'd get an IList<Cat>
or an IList<Zebra>
depending on the type of animal I passed in the type parameter.
Is this possib开发者_开发百科le? If so how?
Yes, something like this is certainly possible using generics. I think you're looking for this:
IList<T> GetAnimalsOfType<T>() where T : Animal {
return dictionary[typeof(T)].OfType<T>().ToList();
}
There's a difference between this and what you mentioned in the question. The type is not passed as an argument. Since the argument is passed at runtime, it doesn't make sense if it returns an strongly typed list. The compiler wouldn't know anyway and you wouldn't be able to use it.
You can use a generic method. It goes something like this:
public IList<T> GetAnimals<T>(){
return this.animals[typeof(T)].Cast<T>().ToList();
}
精彩评论