正确的问题得到通用的扩展方法来工作
-
21-09-2019 - |
题
我试图创建的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);
什么我这里做错了吗?
解决方案
您的代码工作正常,我:
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);
}
}
可不可以给一个类似的短但完整的程序,编译失败?
其他提示
使用
hashSet.UnionWith<Item>(list);
不隶属于 StackOverflow