简体   繁体   English

必须在非泛型静态类中定义扩展方法

[英]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. 如果从参数中删除“this”,它应该可以工作。

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. 因为您的包含类不是静态的,所以Extension方法应该在静态类中。 That class should be non nested as well. 该类也应该是非嵌套的。 Extension Methods (C# Programming Guide) 扩展方法(C#编程指南)

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. 当我删除该方法时,错误就消失了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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