【问题标题】:Extension Method for Generic Class [duplicate]泛型类的扩展方法
【发布时间】:2010-02-18 22:10:05
【问题描述】:

可能的重复:
C# -Generic Extension Method
How do you write a C# Extension Method for a Generically Typed Class

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

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

【问题讨论】:

标签: c# generics extension-methods


【解决方案1】:

扩展任何类

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

扩展特定的泛型类

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

【讨论】:

  • 对我来说,我忘记了需要扩展之后的 。更具体地说,我想为通用 Dictionary 类编写扩展,所以我需要 .
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    当然

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

      • 这段代码不会编译
      • 扩展方法必须是静态方法,不能是泛型。
      • 编译器错误:扩展方法必须定义在非泛型静态类中
      • 这不会编译,因为扩展方法需要在静态非泛型类中
      • 你的类应该是静态的。
      猜你喜欢
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多