C# 泛型类的扩展方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2292597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:09:18  来源:igfitidea点击:

Extension Method for Generic Class

c#genericsextension-methods

提问by Will

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

可能的重复项:
C# -Generic Extension Method如何为泛型类
编写 C# 扩展方法

Is it possible to declare extension methods for generic classes?

是否可以为泛型类声明扩展方法?

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

回答by Asad

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

你如何写一个C#扩展方法对于一般地类型化的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)
    {   
         //...
    }
}

回答by Johannes Rudolph

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

是的,但您忘记了this关键字。查看提供集合上所有 LINQ 运算符的 Queryable。

回答by JaredPar

Sure

当然

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

回答by Stan R.

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)
{
    //...
}