2

HashSetの拡張メソッドAddRangeを作成しようとしているので、次のようなことができます。

var list = new List<Item>{ new Item(), new Item(), new Item() };
var hashset = new HashSet<Item>();
hashset.AddRange(list);

これは私がこれまでに持っているものです:

public static void AddRange<T>(this ICollection<T> collection, List<T> list)
{
    foreach (var item in list)
    {
        collection.Add(item);
    }
}

問題は、AddRangeを使用しようとすると、次のコンパイラエラーが発生することです。

The type arguments for method 'AddRange<T>(System.Collections.Generic.ICollection<T>, System.Collections.Generic.List<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

言い換えれば、私は代わりにこれを使用することになります:

hashset.AddRange<Item>(list);

私はここで何が間違っているのですか?

4

2 に答える 2

29

使用する

hashSet.UnionWith<Item>(list);
于 2009-10-29T20:24:07.017 に答える
3

あなたのコードは私にとってうまく機能します:

using System.Collections.Generic;

static class Extensions
{
    public static void AddRange<T>(this ICollection<T> collection, List<T> list)
    {
        foreach (var item in list)
        {
            collection.Add(item);
        }
    }
}

class Item {}

class Test
{
    static void Main()
    {
        var list = new List<Item>{ new Item(), new Item(), new Item() };
        var hashset = new HashSet<Item>();
        hashset.AddRange(list);
    }
}

コンパイルに失敗する同様の短いが完全なプログラムを提供できますか?

于 2009-10-17T21:18:31.017 に答える