C# 为什么 IList 不支持 AddRange

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11538259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:11:39  来源:igfitidea点击:

Why doesn't IList support AddRange

c#.netilist

提问by Boris Callens

List.AddRange()exists, but IList.AddRange()doesn't.
This strikes me as odd. What's the reason behind this?

List.AddRange()存在,但IList.AddRange()不存在。
这让我觉得很奇怪。这背后的原因是什么?

采纳答案by xanatos

Because an interface shoud be easy to implement and not contain "everything but the kitchen". If you add AddRangeyou should then add InsertRangeand RemoveRange(for symmetry). A better question would be why there aren't extension methods for the IList<T>interface similar to the IEnumerable<T>interface. (extension methods for in-place Sort, BinarySearch, ... would be useful)

因为界面应该易于实现并且不包含“除了厨房之外的所有东西”。如果添加AddRange,则应添加InsertRangeRemoveRange(为了对称)。一个更好的问题是为什么没有IList<T>类似于IEnumerable<T>接口的接口的扩展方法。(就地Sort, BinarySearch, ... 的扩展方法会很有用)

回答by Emilien Mathieu

For those who want to have extension methods for "AddRange", "Sort", ... on IList,

对于那些想要在 IList 上拥有“AddRange”、“Sort”、...的扩展方法的人,

Below is the AddRangeextension method:

下面是AddRange扩展方法:

 public static void AddRange<T>(this IList<T> source, IEnumerable<T> newList)
 {
     if (source == null)
     {
        throw new ArgumentNullException(nameof(source));
     }

     if (newList == null)
     {
        throw new ArgumentNullException(nameof(newList));
     }

     if (source is List<T> concreteList)
     {
        concreteList.AddRange(newList);
        return;
     }

     foreach (var element in newList)
     {
        source.Add(element);
     }
}

I created a small library that does this. I find it more practical than having to redo its extension methods on each project.

我创建了一个小型图书馆来做到这一点。我发现它比必须在每个项目上重做其扩展方法更实用。

Some methods are slower than List but they do the job.

有些方法比 List 慢,但它们可以完成工作。

Here is the GitHub to interest them:

这是他们感兴趣的 GitHub:

IListExtension repository

IListExtension 存储库