Problem getting generic extension method to work correctly
I'm trying to create the extension method AddRange for HashSet so I can do something like this:
var list = new List<Item>{ new I开发者_JS百科tem(), new Item(), new Item() };
var hashset = new HashSet<Item>();
hashset.AddRange(list);
This is what I have so far:
public static void AddRange<T>(this ICollection<T> collection, List<T> list)
{
foreach (var item in list)
{
collection.Add(item);
}
}
Problem is, when I try to use AddRange, I'm getting this compiler error:
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.
In other words, I have to end up using this instead:
hashset.AddRange<Item>(list);
What am I doing wrong here?
Use
hashSet.UnionWith<Item>(list);
Your code works fine for me:
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);
}
}
Could you give a similar short but complete program which fails to compile?
精彩评论