我现在的情况是,我想将字符串数组(类型为String[])中的值添加到一个包含IList<String>的对象中。在MSDN上快速查找后发现,IList<T>的Insert方法只有一种版本,它需要索引和对象T,而不是IEnumerable<T>的版本。这是否意味着我必须编写一个循环来将输入列表中的值放入目标列表中?如果是这样,那么这似乎非常受限制,而且API设计也不太友好。也许我漏掉了什么。在这种情况下,C#专家们会怎么做呢?
因为接口通常是最少的功能,以使其可用,减轻实现者的负担。使用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);