2010-02-18 63 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) 
{ 
    //... 
}