具有通用列表参数的功能

时间:2012-06-29 03:40:45

标签: c# generics

我正在尝试编写一种采用任何类型列表并比较项目的方法。这是我到目前为止所做的,但它没有编译。

protected bool DoListsContainAnyIdenticalRefernces(List<T> firstList, List<T> secondList)
  {
     bool foundMatch = false;
     foreach (Object obj in firstList)
     {
        foreach (Object thing in secondList)
        {
           if (obj.Equals(thing))
           {
              foundMatch = true;
           }
        }
     }
     return foundMatch;
  }

它表示参数中的两个T有错误,if语句中有“obj”和“thing”。

2 个答案:

答案 0 :(得分:1)

如果您不在泛型类中,则需要将通用参数T添加到generic method定义中

  protected bool DoListsContainAnyIdenticalRefernces<T>(
      List<T> firstList, 
      List<T> secondList)
  {
     bool foundMatch = false;
     foreach (T obj in firstList)
     {
        foreach (T thing in secondList)
        {
           if (obj.Equals(thing))
           {
              foundMatch = true;
           }
        }
     }
     return foundMatch;
  }

注意:您可以在方法中使用T而不是Object

答案 1 :(得分:1)

您还可以使用Linq扩展方法Intersect来获得相同的结果。

// to get a list of the matching results
var matchedResults = MyCollection.Intersect(MyOtherCollection);

// to see if there are any matched results
var matchesExist = MyCollection.Intersect(MyOtherCollection).Any();
相关问题