在基类列表中找到派生类 [英] Find a derived class in a list of its base class

查看:92
本文介绍了在基类列表中找到派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个BaseClass列表,并在其中填充了几个派生类的实例(每个派生类中只有一个),这样我们就得到了类似的东西:

So I have a List of BaseClass and I've filled it with several instances of derived classes (only one of each derived class) so that we have something like:

List<BaseClass> myList = new List<BaseClass>();

myList.Add(new DerivedClassA());
myList.Add(new DerivedClassB());
myList.Add(new DerivedClassC());

现在,我希望能够使用以下内容搜索myList:

Now I want to be able to search myList with something like this:

public void FindClass (BaseClass class){ //class is a derived class
   //find index or object of type class
   //so that if class is a DerivedClassB
   //we return the first DerivedClassB in myList 
}

这可能吗?我知道我可以给每个DerivedClass一个name属性,并通过它的名称找到它,但是我不想这样做.

Is this possible? I know I can give each DerivedClass a name property and find it by it's name but I don't want to have to do that.

推荐答案

如果传入DerivedClassB的实例,则可以通过比较传入的实例和实例的实际类型来找到DerivedClassB的所有实例.列表中的实例:

If you pass in an instance of DerivedClassB, you can find all instances of DerivedClassB by comparing the actual type of the instance passed in and of the instances in the list:

public IEnumerable<BaseClass> FindClass (BaseClass @class){ 
    return myList.Where(c => c.GetType() == @class.GetType());
}

这篇关于在基类列表中找到派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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