, 나는 AddRange
(또는 2) 추가에 더 관심이있을 거라고 :
는
public static void AddRange<T>(this ICollection<T> collection,
params T[] items)
{
if(collection == null) throw new ArgumentNullException("collection");
if(items == null) throw new ArgumentNullException("items");
for(int i = 0 ; i < items.Length; i++) {
collection.Add(items[i]);
}
}
public static void AddRange<T>(this ICollection<T> collection,
IEnumerable<T> items)
{
if (collection == null) throw new ArgumentNullException("collection");
if (items == null) throw new ArgumentNullException("items");
foreach(T item in items) {
collection.Add(item);
}
}
params T[]
접근 방식은 AddRange(1,2,3,4,5)
등을 허용하고 IEnumerable<T>
는 LINQ 쿼리와 같은 것들로 사용할 수 있습니다.
당신은 유창하게 API를 사용하려면 제네릭 제약의 적절한 사용에 의해 원래 목록 유형을 유지, 당신은 또한 C# 3.0의 확장 방법으로 Append
을 작성할 수 있습니다
public static TList Append<TList, TValue>(
this TList list, TValue item) where TList : ICollection<TValue>
{
if(list == null) throw new ArgumentNullException("list");
list.Add(item);
return list;
}
...
List<int> list = new List<int>().Append(1).Append(2).Append(3);
(주 그것은 List<int>
)
왜 그냥 컬렉션 클래스에 AddRange (IEnumerable을 항목) 메소드를 추가? –
BFree
패션, 뷰티 & 스타일. 나는 할 수 있었다. 그러나 내가 그것을 또 다른 방법으로 할 수 있는지 궁금하게 생각하고 있었다. – danmine