23

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

4

1 回答 1

38

因为接口通常是使其可用所需的最少功能,以减轻实现者的负担。使用 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<T>现在有AddRange

IList<string> list = ...
string[] arr = {"abc","def","ghi","jkl","mno"};
list.AddRange(arr);
于 2009-07-12T22:56:42.383 回答