例子:我想有一個自定義集合類的ICollection
的Add
方法來實現方法鏈接和流利的語言,因此我可以這樣做:有沒有一種簡單優雅的方式讓ICollection在C#中更加流暢?
randomObject.Add("I").Add("Can").Add("Chain").Add("This").
我能想到的幾個選項,但它們是凌亂並涉及將ICollection包裝在另一個界面中等等。
例子:我想有一個自定義集合類的ICollection
的Add
方法來實現方法鏈接和流利的語言,因此我可以這樣做:有沒有一種簡單優雅的方式讓ICollection在C#中更加流暢?
randomObject.Add("I").Add("Can").Add("Chain").Add("This").
我能想到的幾個選項,但它們是凌亂並涉及將ICollection包裝在另一個界面中等等。
您需要從Add中返回void,因爲它是如何在ICollection中設置的。我相信,這就排除了只有一個參數的鏈式添加方法。
不完全是你想要的,但你可以添加類似這樣的東西到你的自定義集合類型。
public CustomCollectionType Append(string toAdd)
{
this.Add(string toAdd);
return this;
}
然後,你可以這樣做:
customCollection.Append("This").Append("Does").Append("Chain");
希望幫助,
丹
+1使用Append而不是Add。我可以重新裝入的所有地方都有Add void或Item。從來沒有收集。添加返回集合類型打破了慣例。 – 2009-08-28 23:01:30
可以隱藏ICollection.Add在您的自定義集合類方法並返回這一點。
public class MyList<T>:List<T>
{
public new MyList<T> Add(T item)
{
(this as ICollection<T>).Add(item);
return this;
}
}
那麼你可以用鏈接的添加通話新增項目:
MyList<string> strList = new MyList<string>();
strList.Add("Hello").Add(" ").Add("World!");
以這種方式是否仍可以在自定義集合類中實現ICollection? – 2009-08-28 22:49:38
如果您隱式實現ICollection
這將是很高興知道downvotes的原因。 – 2009-08-28 23:08:51
另一種選擇是使用C#集合初始化:
var list = new YourList<String>()
{
"Hello",
"World",
"etc..."
};
你也可以使用一個擴展方法將可與任何ICollection<T>
一起使用,並節省您編寫自己的收藏級別的難度:
public static ICollection<T> ChainAdd<T>(this ICollection<T> collection, T item)
{
collection.Add(item);
return collection;
}
雖然流利的很不錯,我會增加更多的興趣的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);
}
}
的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);
(注它返回List<int>
)
我很困惑...爲什麼這不是最受歡迎的答案呢? – 2009-08-29 08:33:33
無意冒犯,但也許你會喜歡VB.NET
這更有利於「自然語言」程序比C#是。
在VB中。NET你有「與」結構,可以讓你做的事:
With myCollection
.Add("Hello")
.Add("There")
.Add("My")
.Add("Name")
.Add("Is")
.Add("Silky")
.Sort()
End With
爲什麼不只是添加的AddRange(IEnumerable的項目)方法到您的收藏類? –
BFree
2009-08-28 22:27:11
時尚,美容,風格。我可以,但我想知道如果我能做到另一種方式。 – danmine 2009-08-28 22:42:07