让通用扩展方法正常工作的问题

Dan*_* T. 2 c# generics extension-methods list hashset

我正在尝试为HashSet创建扩展方法AddRange,所以我可以这样做:

var list = new List<Item>{ new Item(), new Item(), new Item() };
var hashset = new HashSet<Item>();
hashset.AddRange(list);
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止:

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

问题是,当我尝试使用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);
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

小智 29

使用

hashSet.UnionWith<Item>(list);
Run Code Online (Sandbox Code Playgroud)

  • 不,这不对.UnionWith具有与List.AddRange类似的含义.你似乎把它与IntersectWith混合在一起. (6认同)