0

あらゆる種類のリストを取得し、そこにあるアイテムを比較するメソッドを作成しようとしています。これが私がこれまでに持っているものですが、コンパイルされません。

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;
  }

パラメータ内の2つのTと、ifステートメント内の「obj」と「thing」にエラーがあることを示しています。

4

2 に答える 2

1

ジェネリック クラス内にいない場合は、ジェネリック引数Tジェネリック メソッド定義に追加する必要があります。

  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

于 2012-06-29T03:50:38.900 に答える
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();
于 2012-06-29T03:52:03.663 に答える