传递和处理包含相同基类型对象的List <>类型

Chr*_*sBD 0 c# collections inheritance

考虑以下类:

class TypeA;
class TypeB : TypeA;
class TypeC : TypeA;
class TypeD : TypeA;
Run Code Online (Sandbox Code Playgroud)

以及List <>类型:

List<TypeB> listTypeB;
List<TypeC> listTypeC;
List<TypeD> listTypeD;
Run Code Online (Sandbox Code Playgroud)

现在,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;
}
Run Code Online (Sandbox Code Playgroud)

mqp*_*mqp 5

是.您需要使用约束使"包含"方法通用,以便您只能对源自的对象进行操作TypeA(因此具有Prop1:)

bool ContainsProp1<T>(Object1 searchFor, List<T> listToSearch) where T : TypeA
{
   bool found = false;

   for(int i = 0; (i < listToSearch.Count) & !found; i++)
   {
      found = listToSearch[i].Prop1 == searchFor;
   }
   return found;
}
Run Code Online (Sandbox Code Playgroud)

然后你的第一个方法应该按原样编译.