使泛型扩展方法正常工作时出现问题 [英] Problem getting generic extension method to work correctly

查看:112
本文介绍了使泛型扩展方法正常工作时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var list =新的List< Item> {new Item(),new Item(),new Item()}; 
var hashset = new HashSet< Item>();
hashset.AddRange(list);

这就是我到目前为止:

< pre $ public static void AddRange< T>(此ICollection< T>集合,List< T>列表)
{
foreach(var list in list)
{
collection.Add(item);




$ b

问题是,当我尝试使用AddRange时,I 'm得到这个编译器错误:

方法'AddRange< T>(System.Collections.Generic.ICollection< T> System.Collections.Generic.List< T>)'不能从使用中推断出来。尝试明确指定类型参数。



换句话说,我必须最终使用它:

  hashset.AddRange< Item>(list); 

我在这里做错了什么?

解决方案

你的代码适用于我:

使用System.Collections.Generic;

  
$ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆