相关疑难解决方法(0)

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

我正在尝试为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)

我在这做错了什么?

c# generics extension-methods list hashset

2
推荐指数
1
解决办法
1957
查看次数

标签 统计

c# ×1

extension-methods ×1

generics ×1

hashset ×1

list ×1