Extension Method for Generic Class [duplicate]

2019-04-04 15:20发布

Possible Duplicates:
C# -Generic Extension Method
How do you write a C# Extension Method for a Generically Typed Class

Is it possible to declare extension methods for generic classes?

public class NeedsExtension<T>
{
    public NeedsExtension<T> DoSomething(T obj)
    {
        // ....
    }
}

4条回答
时光不老,我们不散
2楼-- · 2019-04-04 15:53

Yes, but you forgot the this keyword. Look at Queryable that provides all the LINQ operators on collections.

查看更多
干净又极端
3楼-- · 2019-04-04 16:03

Sure

public static void SomeMethod<T>(this NeedsExtension<T> value) {
  ...
}
查看更多
看我几分像从前
4楼-- · 2019-04-04 16:10

To extend any class

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

To extend a specific generic class

public static NeedExtension<T> DoSomething<T>(this NeedExtension<T> obj)
{
    //...
}
查看更多
Lonely孤独者°
5楼-- · 2019-04-04 16:17

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

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)
    {   
         //...
    }
}
查看更多
登录 后发表回答