为什么 IList没有采用 IEnumerable的 Insert 方法?

发布于 2024-07-26 23:38:00 字数 270 浏览 3 评论 0原文

我现在的情况是,我只想将字符串数组(类型为 String[])中的值附加到具有 IList的对象。 快速查找 MSDN 发现 IList的 Insert 方法只有一个采用索引和对象 T 的版本,而没有采用 IEnumerable的版本。 而不是 T。这是否意味着我必须在输入列表上编写一个循环才能将值放入目标列表中? 如果是这样的话,对我来说,API 设计似乎非常有限,而且非常不友好。 也许,我错过了一些东西。 在这种情况下,C# 专家会做什么?

I'm in a situation where I just want to append values in string array (type String[]) to an object with IList<String>. A quick look-up on MSDN revealed that IList<T>'s Insert method only has a version which takes an index and an object T, and does not have a version which takes IEnumerable<T> instead of T. Does this mean that I have to write a loop over an input list to put values into the destination list? If that's the case, it seems very limiting and rather very unfriendly API design for me. Maybe, I'm missing something. What does C# experts do in this case?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蝶…霜飞 2024-08-02 23:38:00

因为接口通常是使其可用所需的最少功能,以减轻实现者的负担。 使用 C# 3.0,您可以将其添加为扩展方法:

public static void AddRange<T>(this IList<T> list, IEnumerable<T> items) {
    if(list == null) throw new ArgumentNullException("list");
    if(items == null) throw new ArgumentNullException("items");
    foreach(T item in items) list.Add(item);
}

等等; IList 现在有 AddRange

IList<string> list = ...
string[] arr = {"abc","def","ghi","jkl","mno"};
list.AddRange(arr);

Because an interface is generally the least functionality required to make it usable, to reduce the burden on the implementors. With C# 3.0 you can add this as an extension method:

public static void AddRange<T>(this IList<T> list, IEnumerable<T> items) {
    if(list == null) throw new ArgumentNullException("list");
    if(items == null) throw new ArgumentNullException("items");
    foreach(T item in items) list.Add(item);
}

et voila; IList<T> now has AddRange:

IList<string> list = ...
string[] arr = {"abc","def","ghi","jkl","mno"};
list.AddRange(arr);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文