如何使用任意类型的成员返回一个IList [英] how to return an IList with members of an arbitrary type

查看:160
本文介绍了如何使用任意类型的成员返回一个IList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这甚至有可能,但这里有云:我有一个类动物园持有动物类型的字典 - >动物名单。 。例如

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}



斑马动物的子类。现在动物园有一个方法的IList<动物> GetAnimalsOfType(type类型)

Cat and Zebra are subclasses of Animal. Now Zoo has a method IList<Animal> GetAnimalsOfType(Type type).

我想返回值是动物的请求的类型,因此而不是得到的IList<动物> ; 我会得到一个的IList<猫> 的IList<斑马> 视对动物的类型我传递的类型参数。

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 possible? 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.

这篇关于如何使用任意类型的成员返回一个IList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆