2010-02-18 92 views

回答

0

How do you write a C# Extension Method for a Generically Typed Cla SS

public static class NeedsExtension<T> 
{ 
    public static string DoSomething <T>(this MyType<T> v) 
    { return ""; } 

    // OR 
    public static void DoSomething <T>(this MyType<T> v) 
    { 
     //... 
    } 
} 
+6

这段代码不会编译 – Dmitry

+0

扩展方法必须是静态方法,不是可以是通用类型。 – W92

+0

编译错误:扩展方法必须在非泛型静态类中定义 – Nebula

3

是的,但你忘了this关键字。看看Queryable,它提供了集合上的所有LINQ操作符。

1

不确定

public static void SomeMethod<T>(this NeedsExtension<T> value) { 
    ... 
} 
25

要扩展的任何类

public static class Extensions 
{ 
    public static T DoSomething<T>(this T obj) 
    { 
     //... 
    } 
} 

要扩展的特异性通用类

public static NeedExtension<T> DoSomething<T>(this NeedExtension<T> obj) 
{ 
    //... 
}