使泛型扩展方法正常工作时出现问题 [英] Problem getting generic extension method to work correctly
问题描述
var list =新的List< Item> {new Item(),new Item(),new Item()};
var hashset = new HashSet< Item>();
hashset.AddRange(list);
这就是我到目前为止: 问题是,当我尝试使用AddRange时,I 'm得到这个编译器错误: 换句话说,我必须最终使用它: 我在这里做错了什么? 你的代码适用于我:
< pre $ public static void AddRange< T>(此ICollection< T>集合,List< T>列表)
{
foreach(var list in list)
{
collection.Add(item);
$ b
方法'AddRange< T>(System.Collections.Generic.ICollection< T> System.Collections.Generic.List< T>)'不能从使用中推断出来。尝试明确指定类型参数。
hashset.AddRange< Item>(list);
$ b静态类扩展
{
public static void AddRange< T>(此ICollection< T>集合,List< T>列表)
{
foreach(var中的项目)
{
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);
$ b你可以给一个类似的简短但完整的程序,编译?
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?
解决方案 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?
这篇关于使泛型扩展方法正常工作时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!