Mik*_*e_G 7 .net c# extension-methods method-chaining
是否可以创建一个返回调用扩展方法的实例的扩展方法?
我想为继承的任何东西都有一个扩展方法ICollection<T>
,返回该对象.就像jQuery总是返回jquery对象一样.
public static object AddItem<T>(this ICollection<T> collection, T itemToAdd)
{
collection.Add(itemToAdd);
return collection;
{
Run Code Online (Sandbox Code Playgroud)
我想象上面的内容,但我不知道如何回到父母的"this"对象类型来使用这样的东西:
List<int> myInts = new List<int>().AddItem(5);
Run Code Online (Sandbox Code Playgroud)
编辑:只是想明确我希望有一个通用约束解决方案.
Ste*_*ary 13
如果需要返回特定类型,可以使用通用约束:
public static TCollection AddItem<TCollection, TElement>(
this TCollection collection,
TElement itemToAdd)
where TCollection : ICollection<TElement>
{
collection.Add(itemToAdd);
return collection;
}
Run Code Online (Sandbox Code Playgroud)
我测试了它,它在VS2010中工作.
更新(关于jQuery):
jQuery链接非常有效,因为JavaScript使用动态类型.C#4.0支持dynamic
,所以你可以这样做:
public static dynamic AddItem<T>(this ICollection<T> collection, T itemToAdd)
{
collection.Add(itemToAdd);
return collection;
}
Run Code Online (Sandbox Code Playgroud)
但是,我建议使用通用约束版本,因为它更安全,更高效,并允许返回类型的IntelliSense.在更复杂的场景中,通用约束并不总能表达您的需求; 在这些情况下,dynamic
可以使用(虽然它不会绑定到其他扩展方法,因此它不适用于链接).