سؤال

أحاول إنشاء Addrange طريقة التمديد لـ Hashset حتى أتمكن من فعل شيء مثل هذا:

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<T>(System.Collections.Generic.ICollection<T>, System.Collections.Generic.List<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

بمعنى آخر ، يجب أن ينتهي بي الأمر باستخدام هذا بدلاً من ذلك:

hashset.AddRange<Item>(list);

ماذا أفعل خطأ هنا؟

هل كانت مفيدة؟

المحلول

رمزك يعمل بشكل جيد بالنسبة لي:

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

هل يمكن أن تعطي برنامجًا قصيرًا ولكنه كاملًا يفشل في التجميع؟

نصائح أخرى

يستخدم

hashSet.UnionWith<Item>(list);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top