【发布时间】:2009-10-17 21:13:32
【问题描述】:
我正在尝试为 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);
我在这里做错了什么?
【问题讨论】:
-
奇怪,我将您的代码 sn-ps(以及 Item 的空定义)粘贴到了一个新的控制台项目中,它对我有用。
-
这应该可以正常工作...您可以发布一个完整的代码来说明问题吗?附带说明:你应该将参数声明为
IEnumerable<T>,而不是List<T>,它会给你更多的灵活性
标签: c# generics list extension-methods hashset