是否有一种简单而优雅的方式使ICollection在C#中更流畅?

dan*_*ine 4 c# fluent icollection method-chaining

例如:我想有Add方法ICollection的自定义集合类来实现方法链接和流利的语言,所以我能做到这一点的:

randomObject.Add("I").Add("Can").Add("Chain").Add("This").
Run Code Online (Sandbox Code Playgroud)

我可以想到一些选项,但它们很混乱,并涉及将ICollection包装在另一个界面中等等.

Mar*_*ell 11

虽然流利很好,但我更感兴趣的是添加一个AddRange(或两个):

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

params T[]方法允许AddRange(1,2,3,4,5)等,并IEnumerable<T>允许使用LINQ查询之类的东西.

如果要使用流畅的API,您还可以通过适当使用通用约束,Append在C#3.0中编写一个扩展方法来保留原始列表类型:

    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);
Run Code Online (Sandbox Code Playgroud)

(注意它返回List<int>)


Cur*_*uys 5

您还可以使用可以与任何一个一起使用的扩展方法,ICollection<T>并使您免于编写自己的集合类:

public static ICollection<T> ChainAdd<T>(this ICollection<T> collection, T item)
{
  collection.Add(item);
  return collection;
}
Run Code Online (Sandbox Code Playgroud)