【问题标题】:Error: Extension method must be defined in a non-generic static class错误:必须在非泛型静态类中定义扩展方法
【发布时间】:2012-01-01 21:56:26
【问题描述】:

我在类名处收到以下编译错误。

Extension method must be defined in a non-generic static class

我没有使用普通课程。这可能是什么原因。我不知道也不想使用扩展方法。

【问题讨论】:

  • 没有您的代码,我们无能为力。我最好的猜测是你不小心在参数列表的某个地方输入了“this”。
  • 请显示你的类的方法签名。
  • 哇!!!!!!那是错误!非常感谢!
  • @Jules,您应该将此作为答案发布。

标签: c# extension-methods


【解决方案1】:

根据要求,这是我的评论作为答案:

没有您的代码,我们无能为力。我最好的猜测是你不小心在参数列表的某个地方输入了“this”。

【讨论】:

  • 谢谢!帮了我很多..我正在寻找做得不好的地方..并没有找到,直到你写了关于这个..所以我搜索了“这个”并发现它不是他的地方:)
【解决方案2】:

扩展方法示例

public static class ExtensionMethods {
 public static object ToAnOtherObject(this object obj) {
  // Your operation here
 }
}

【讨论】:

    【解决方案3】:

    我有同样的问题,并解决如下。我的代码是这样的:

    public static class ExtensionMethods 
    {
        public static object ToAnOtherObject(this object obj) 
        {
            // Your operation here
        }
    }
    

    我把它改成了

    public static class ExtensionMethods 
    {
        public static object ToAnOtherObject(object obj) 
        {
            // Your operation here
        }
    }
    

    我删除了方法参数的“this”字样。

    【讨论】:

      【解决方案4】:

      我猜这与您的previous list question 相关;如果是这样,我提供的示例一个扩展方法,应该是:

      public static class LinkedListUtils { // name doesn't matter, but must be
                                            // static and non-generic
          public static IEnumerable<T> Reverse<T>(this LinkedList<T> list) {...}
      }
      

      此实用程序类不需要与消费类相同,但扩展方法可以用作list.Reverse()

      如果您不想将其作为扩展方法,则可以将其设为本地静态方法 - 只需从第一个参数中去掉“this”即可:

      public static IEnumerable<T> Reverse<T>(LinkedList<T> list) {...}
      

      并用作:

      foreach(var val in Reverse(list)) {...}
      

      【讨论】:

        【解决方案5】:

        创建扩展方法时需要考虑以下几点:

        1. 定义扩展方法的类必须是非泛型static
        2. 每个扩展方法都必须是static 方法
        3. 扩展方法的第一个参数应该使用this关键字。

        【讨论】:

          【解决方案6】:

          发布您的代码怎么样?扩展方法是通过在静态方法的第一个参数前面加上 this 来声明的。由于您不会使用扩展方法,因此我怀疑您不小心以this 开头的参数列表。

          寻找类似的东西:

          void Method(this SomeType name)
          {
          }
          

          【讨论】:

            猜你喜欢
            • 2023-03-10
            • 2016-10-25
            • 1970-01-01
            • 1970-01-01
            • 2014-10-31
            相关资源
            最近更新 更多