Problem getting generic extension method to work c

2019-07-24 17:42发布

I'm trying to create the extension method AddRange for HashSet so I can do something like this:

var list = new List<Item>{ new Item(), 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?

2条回答
再贱就再见
2楼-- · 2019-07-24 18:14

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?

查看更多
forever°为你锁心
3楼-- · 2019-07-24 18:16

Use

hashSet.UnionWith<Item>(list);
查看更多
登录 后发表回答