Extension method must be defined in non-generic static class

丶灬走出姿态 提交于 2019-12-05 09:53:04

问题


Error at:

public partial class Form2 : Form

Probable cause:

public static IChromosome To<T>(this string text)
{
    return (IChromosome)Convert.ChangeType(text, typeof(T));
}

Attempted (without static keyword):

public IChromosome To<T>(this string text)
{
    return (IChromosome)Convert.ChangeType(text, typeof(T));
}

回答1:


If you remove "this" from your parameters it should work.

public static IChromosome To<T>(this string text)

should be:

public static IChromosome To<T>(string text)



回答2:


The class containing the extension must be static. Yours are in:

public partial class Form2 : Form

which is not a static class.

You need to create a class like so:

static class ExtensionHelpers
{
    public static IChromosome To<T>(this string text) 
    { 
        return (IChromosome)Convert.ChangeType(text, typeof(T)); 
    } 
}

To contain the extension methods.




回答3:


My issue was caused because I created a static method inside the partial class:

public partial class MainWindow : Window{

......

public static string TrimStart(this string target, string trimString)
{
    string result = target;

    while (result.StartsWith(trimString)){
    result = result.Substring(trimString.Length);
    }

    return result;
    }
} 

When I removed the method, the error went away.




回答4:


Because your containing class is not static, Extension method should be inside a static class. That class should be non nested as well. Extension Methods (C# Programming Guide)



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

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