如何返回具有任意类型成员的IList

Joh*_*nny 3 c# generics

我不确定这是否可能,但是这里有:我有一个类Zoo,其中包含动物类型字典 - >动物列表.例如

Cat Type -> {Cat1, Cat2}
Zebra Type -> {Zebra1, Zebra2}
Run Code Online (Sandbox Code Playgroud)

Cat并且Zebra是.的子类Animal.现在Zoo有一个方法IList<Animal> GetAnimalsOfType(Type type).

我希望返回值是所请求动物的类型,因此IList<Animal>我不会得到一个IList<Cat>或者IList<Zebra>取决于我在类型参数中传递的动物类型.

这可能吗?如果是这样的话?

Meh*_*ari 11

是的,这样的东西肯定可以使用泛型.我想你正在寻找这个:

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

这和你在问题中提到的内容有所不同.该类型作为参数传递.由于参数是在运行时传递的,因此如果返回强类型列表则没有意义.编译器无论如何都不会知道,你将无法使用它.