我正在尝试为 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);
我在这里做错了什么?
Use
hashSet.UnionWith<Item>(list);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)