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

时间:2012-05-02 10:49:32

标签: c# .net compiler-errors extension-methods

错误:

public partial class Form2 : Form

可能原因:

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

尝试(没有静态关键字):

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

4 个答案:

答案 0 :(得分:32)

如果从参数中删除“this”,它应该有效。

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

应该是:

public static IChromosome To<T>(string text)

答案 1 :(得分:19)

包含扩展名的类必须是静态的。你在:

public partial class Form2 : Form

这不是静态类。

您需要创建一个类似的类:

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

包含扩展方法。

答案 2 :(得分:1)

因为包含的类不是静态的,所以Extension方法应该在静态类中。该类也应该是非嵌套的。 Extension Methods (C# Programming Guide)

答案 3 :(得分:1)

我的问题是因为我在分部类中创建了一个静态方法:

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

当我删除该方法时,错误就消失了。

相关问题