【发布时间】:2009-06-04 13:52:10
【问题描述】:
考虑以下类:
class TypeA;
class TypeB : TypeA;
class TypeC : TypeA;
class TypeD : TypeA;
和以下 List 类型:
List<TypeB> listTypeB;
List<TypeC> listTypeC;
List<TypeD> listTypeD;
现在 TypeA 有一个 Object1 类型的属性 Prop1,我想找到哪个列表中存储了一个具有给定值 Prop1 的项目。有没有一种方法可以让我执行以下操作,这样我只需要编写一次搜索代码?
bool LocateInAnyList(Object1 findObj)
{
bool found = false;
found = ContainsProp1(findObj, listTypeB);
if(!found)
{
found = ContainsProp1(findObj, listTypeC);
}
if(!found)
{
found = ContainsProp1(findObj, listTypeD);
}
return found;
}
bool ContainsProp1(Object1 searchFor, List<TypeA> listToSearch)
{
bool found = false;
for(int i = 0; (i < listToSearch.Count) & !found; i++)
{
found = listToSearch[i].Prop1 == searchFor;
}
return found;
}
【问题讨论】:
标签: c# inheritance collections