T在班?的AddRange ICollection的? [英] T in class? AddRange ICollection?

查看:153
本文介绍了T在班?的AddRange ICollection的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试做静态类,添加到ICollection的,但我得到了一些问题,我似乎无法克服。这就是我如何让这样我就可以通过在方法ICollection的?原因T是该说这是不可能解决的。

然后我不知道有没有办法做到的AddRange对ICollection的?

我在想是这样的,但莫比我是出路,我的心呢?

 公共静态的ICollection< T>增加(这IEnumerable的< T>名单)
    {
        ICollection的< T>集合= NULL;

        返回collection.AddRange(名单);
    }
 

解决方案

没有,的ICollection< T> 不具有的AddRange 方法 - 即使它做了,你会尝试取消引用这将抛出一个的NullReferenceException 。您还没有指定一个集合添加列表...到底是什么你想怎么办?

您可以创建(比如)一个新的名单,其中,T> - 和一个已经有一个构造函数,可以采取一个的IEnumerable&LT的好处; T>

 公共静态的ICollection< T>添加< T>(这IEnumerable的< T>名单)
{
    返回新的List< T>(名单);
}
 

不过,你真的只是重新实现这一点 Enumerable.ToList(),并给它一个不同的返回类型...

如果你想要的一切添加到现有的收藏,你可能会想是这样的:

 公共静态的ICollection< T> AddTo就< T>(这IEnumerable的< T>清单,
                                      ICollection的< T>采集)
{
    的foreach(列表中的牛逼项)
    {
        collection.Add(项目);
    }
    返回集合;
}
 

I try to do static class, add to icollection but i got some issues i cant seem to overcome. that is how i get so i can pass a ICollection in the method? cause T is that say it can not be resolved.

and then i wonder is there a way to do AddRange on icollection?

i was thinking of something like this but maby i am way out of my mind with it?

public static ICollection<T> add(this IEnumerable<T> list)
    {
        ICollection<T> collection = null;

        return collection.AddRange(list);            
    }

解决方案

No, ICollection<T> doesn't have an AddRange method - and even if it did, you'd be trying to dereference null which will throw a NullReferenceException. You haven't specified a collection to add the list to... what exactly are you trying to do?

You could create (say) a new List<T> - and that has the benefit of already having a constructor which can take an IEnumerable<T>:

public static ICollection<T> Add<T>(this IEnumerable<T> list)
{
    return new List<T>(list);            
}

However, at that point you've really just reimplemented Enumerable.ToList() and given it a different return type...

If you want to add everything to an existing collection, you might want something like this:

public static ICollection<T> AddTo<T>(this IEnumerable<T> list,
                                      ICollection<T> collection)
{
    foreach (T item in list)
    {
        collection.Add(item);
    }
    return collection;
}

这篇关于T在班?的AddRange ICollection的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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