上课T?添加范围 ICollection?
我尝试做静态类,添加到 icollection 但我遇到了一些我似乎无法克服的问题。这就是我得到的方式,以便我可以在方法中传递 ICollection?原因T是说它无法解决。
然后我想知道有没有办法在 icollection 上执行 AddRange ?
我正在考虑类似的事情,但也许我已经疯了?
public static ICollection<T> add(this IEnumerable<T> list)
{
ICollection<T> collection = null;
return collection.AddRange(list);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,
ICollection
没有AddRange
方法 - 即使有,您也会尝试取消引用null
将抛出一个NullReferenceException
。您尚未指定要将列表添加到的集合...您到底想做什么?您可以创建(比如说)一个新的
List
- 这样做的好处是已经有了一个可以采用IEnumerable
的构造函数:但是,在那点你实际上只是重新实现了
Enumerable.ToList()
并给它一个不同的返回类型...如果你想将所有内容添加到现有集合中,你可能需要这样的东西:
No,
ICollection<T>
doesn't have anAddRange
method - and even if it did, you'd be trying to dereferencenull
which will throw aNullReferenceException
. 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 anIEnumerable<T>
: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:
如果我理解正确的话,您想将
IEnumerable
添加到空集合中。这样做不是更容易吗:
甚至:
If I understand correctly you want to add a
IEnumerable<T>
to an empty collection.Wouldn't it be easier to just do:
Or even:
其他方法似乎假设您的 ICollection 为空和/或您的 ICollection 是一种列表类型。但是,如果您想要 AddRange,那么您可以按如下方式扩展 ICollection 类:
但是请注意,由于 List 实现了 ICollection,因此在直接处理 List 对象时可能会导致歧义(尽管我还没有测试编译器是否会能够解决它——不过,我的直觉反应是它应该,因为 AddRange 是 List 的成员,并且编译器在查看扩展之前将首先遍历成员函数,但如果我错了,我相信有人会纠正我)。
The other ways seem to assume that your ICollection is empty and/or your ICollection is a type of List. However, if you want AddRange, then you can Extend the ICollection class as follows:
Note, however, that since List impliments ICollection, this may cause ambiguity when dealing directly with List objects (though I haven't tested yet if the compiler will be able to resolve it--my gut reaction is that it should, though, since AddRange is a member of List and the compiler will go through member functions first before looking at extensions, but if I'm wrong I'm sure someone will correct me).
根据源列表的集合类型,替代方法是使用
List (T).ForEach
,如:但是,其可读性为 容易引起争议。
Depending on the collection type of your source list an alternative approach is to use
List(T).ForEach
, as in:However, the readability of this is easy to dispute.