How to return an IList with members of an arbitrary type

I'm not sure if this is possible, but here it goes: I have a class Zoothat contains the Animal Type -> List of Animals dictionary. eg.

Cat Type -> {Cat1, Cat2}
Zebra Type -> {Zebra1, Zebra2}

Catand Zebraare subclasses Animal. Now Zoohas a method IList<Animal> GetAnimalsOfType(Type type).

I would like the returned value to be of the type of the requested animal, so instead of getting it, IList<Animal>I would receive, IList<Cat>or IList<Zebra>depending on the type of animal, which I passed into the type parameter.

Is it possible? If so, how?

+3
source share
2 answers

Yes, something like this, of course, is possible using generics. I think you are looking for this:

IList<T> GetAnimalsOfType<T>() where T : Animal {
    return dictionary[typeof(T)].OfType<T>().ToList();
}

, . . , , . , .

+11

. :

public IList<T> GetAnimals<T>(){
    return this.animals[typeof(T)].Cast<T>().ToList();
}
+2

Source: https://habr.com/ru/post/1730053/


All Articles