泛型类的扩展方法

Wil*_*ill 13 c# generics extension-methods

可能重复:
C# - 通用扩展方法如何为通用
类型类编写C#扩展方法

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

public class NeedsExtension<T>
{
    public NeedsExtension<T> DoSomething(T obj)
    {
        // ....
    }
}
Run Code Online (Sandbox Code Playgroud)

Sta*_* R. 34

扩展任何课程

public static class Extensions
{
    public static T DoSomething<T>(this T obj)
    {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

扩展特定的泛型类

public static NeedExtension<T> DoSomething<T>(this NeedExtension<T> obj)
{
    //...
}
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,我忘记了 NeedExtension 之后的 &lt;T&gt;。更具体地说,我想为通用 Dictionary 类编写扩展,所以我需要 &lt;TKey,TValue&gt;。 (2认同)

Joh*_*lph 5

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


Asa*_*sad -5

如何为通用类型类编写 C# 扩展方法

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)
    {   
         //...
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这段代码不会编译 (11认同)