你似乎有2倍相互冲突的目标,并把它归结为您希望您的扩展方法返回什么:
从你的使用例子,在这里引用:
List<int> myInts = new List<int>().AddItem(5);
你让它看起来像你想要返回集合。在任何情况下,分配仍然不会没有科协工作,因为你的扩展方法需要有ICollection的返回类型,就像这样:
public static ICollection<T> AddItem<T>(this ICollection<T> collection, T itemToAdd)
{
collection.Add(itemToAdd);
return collection;
}
这将允许你这样做:
List<int> myList = (List<int>) new List<int>().AddItem(5);
现在,如果您希望返回添加的对象,那么您仍不应该有返回类型object
。你应该充分利用你的泛型类型参数,并返回T
,像这样:
public static T AddItem<T>(this ICollection<T> collection, T itemToAdd)
{
collection.Add(itemToAdd);
return itemToAdd;
}
但是,如果你回国加入该项目,你将不能够像这条产业链:
List<int> myList = (List<int>) new List<int>().AddItem(5);
,因为AddItem(5)
返回类型不 ICollection的,但它是T
(int
,在这种情况下)。您仍然可以连锁不过,就在增值的,就像这样:
List<int> myList = new List<int>();
myList.AddItem(5).DoSomethingWithMyInt(); // Not very useful in this case
这似乎是第一个场景是比较有用的(返回集合),因为它允许您链,马上最初的赋值语句。这里有一个更大的示例:
List<int> myList = new List<int>().AddItem(1).AddItem(2).ToList();
谢谢。起初,我这样做,但不喜欢2泛型规范。但是,我想到了,因为类型是TCollection隐含的,你实际上不需要在代码中指定它。 – 2010-07-09 20:12:17
对。使用它的代码正是你在你的问题中所拥有的;没有明确的类型参数是必要的。我也更新了关于jQuery的答案。 – 2010-07-09 20:20:44