C# 找不到 char 结构的扩展方法

C# Cannot find extension method for char struct

基本上,我写了这个扩展方法:

public static class Extensions 
{
    public static bool IsMaths(this Char it)
    {
        if (char.IsDigit(it) || char.IsControl(it)) { return true; }
        foreach (char each in new char[] { '-', '+', '(', ')', '/', '*', '%', '^', '.' })
        {
            if (each.Equals(it)) { return true; }
        }
        return false;
    }
}

当我尝试调用它时:

else if (!Char.IsMaths(e.KeyChar)) { e.Handled = true; }

Visual Studio 给我的错误是 'char' does not contain a definition for 'IsMaths'。为什么会这样?

Visual Studio gives me the error that 'char' does not contain a definition for 'IsMaths'. Why is this so?

因为扩展方法适用于类型实例,而不是类型本身。您正在使用静态 char 方法,这就是不可能的原因。

您想做的事情:

else if (!e.KeyChar.IsMaths()) { e.Handled = true; }