【问题标题】:Problem getting generic extension method to work correctly使通用扩展方法正常工作的问题
【发布时间】:2009-10-17 21:13:32
【问题描述】:

我正在尝试为 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&lt;T&gt;(System.Collections.Generic.ICollection&lt;T&gt;, System.Collections.Generic.List&lt;T&gt;)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

换句话说,我最终不得不改用这个:

hashset.AddRange<Item>(list);

我在这里做错了什么?

【问题讨论】:

  • 奇怪,我将您的代码 sn-ps(以及 Item 的空定义)粘贴到了一个新的控制台项目中,它对我有用。
  • 这应该可以正常工作...您可以发布一个完整的代码来说明问题吗?附带说明:你应该将参数声明为IEnumerable&lt;T&gt;,而不是List&lt;T&gt;,它会给你更多的灵活性

标签: c# generics list extension-methods hashset


【解决方案1】:

使用

hashSet.UnionWith<Item>(list);

【讨论】:

  • 谢谢 - 我没注意到。
  • UnionWish 将 HashSet 修改为仅包含常见元素。 AddRange 应该将特定集合中的 ell 元素添加到 HasSet。
  • 不,不是。 UnionWith 与 List.AddRange 具有相似的含义。您似乎将它与 IntersectWith 混合在一起。
【解决方案2】:

你的代码对我来说很好用:

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);
    }
}

你能不能给出一个类似的短而完整但编译失败的程序?

【讨论】:

  • 我发现了问题,但与扩展方法无关。相反,我试图将 List 隐式转换为 HashSet,但这不起作用并导致扩展方法也无法隐式转换它。
  • 其他人,在您的代码中使用这个接受的答案之前,请使用 UnionWith 查看下面的答案。
  • 如果提供了起始索引和计数,是否可以从哈希集中检索一系列元素,就像列表的 GetRange() 一样?
  • @inquisitive:这没有任何逻辑意义,因为哈希集没有按逻辑排序。如果您添加一个项目,则完全有可能将整个集合重新排序。您可以使用 LINQ 中的 Skip/Take,但这样做表明您不应该使用 HashSet 开始。
猜你喜欢
  • 1970-01-01
  • 2012-07-05
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
  • 2018-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多