简体   繁体   中英

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

I get the following compilation error at the class name.

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

I am not using normal class. What could be the reason for this. I don't know and don't want to use extension methods.

As requested, here is my comment as an answer:

Without your code there isn't much we can do. My best guess is that you accidentally typed "this" somewhere in a parameter list.

Sample for extension method

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

I had the same problem, and solved it as follows. My code was something like this:

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

and I changed it to

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

I removed the word "this" of the parameter of the method.

I'm guessing this relates to your previous list question ; if so, the example I provided is an extension method, and would be:

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

This utility class does not need to be the same as the consuming class, but extension methods is how it is possible to use as list.Reverse()

If you don't want it as an extension method, you can just make it a local static method - just take away the "this" from the firstparameter:

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

and use as:

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

The following points need to be considered when creating an extension method:

  1. The class which defines an extension method must be non-generic and static
  2. Every extension method must be a static method
  3. The first parameter of the extension method should use the this keyword.

How about posting your code? Extension methods are declared by preceding the first parameter of a static method with this. Since you don't won't to use an extension method, I suspect you accidentally started a parameter list with this .

Look for something like:

void Method(this SomeType name)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM