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

試著忘記壹切 提交于 2019-12-25 19:58:48

问题


enter image description here public class countryController : Controller //Error :Extension method must be defined in a non-generic static class


回答1:


You can't define an extension method inside a non-static class countryController

This is not allowed:

public class MyExtensions
{
    public static void SomeExtension(this String str)
    {

    }
}

This is allowed:

public static class MyExtensions
{
    public static void SomeExtension(this String str)
    {

    }
}

You have a method whose first parameter starts with this, you need to find it and either modify it by removing the this or move it to a static helper class.

According to C# Specifications:

10.6.9 Extension methods

When the first parameter of a method includes the this modifier, that method is said to be an extension method. Extension methods can only be declared in non-generic, non-nested static classes. The first parameter of an extension method can have no modifiers other than this, and the parameter type cannot be a pointer type.




回答2:


Add keyword static to class declaration:

// this is a non-generic static class

public static class yourclass
{
}

Following points need to be considered when creating an extension method:

The class which defines an extension method must be non-generic, static and non-nested

Every extension method must be a static method

The first parameter of the extension method should use the this keyword.



来源:https://stackoverflow.com/questions/37983239/error-extension-method-must-be-defined-in-a-non-generic-static-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!