简体   繁体   中英

Extension method must be defined in non-generic static class

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));
}

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)

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.

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)

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.

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