Extension method must be defined in non-generic st

2020-06-07 04:54发布

问题:

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)