非法声明属性和静态函数。为什么?

时间:2010-10-13 12:18:45

标签: c# static properties

可以解释为什么我在这段代码上出现此错误?

  

错误1类型   'ConsoleApplication1.TestClass'   已经包含了一个定义   'IsThisOK'

class TestClass
    {
        public bool IsThisOK { get; set; }

        public static bool IsThisOK(string str)
        {
            return true;
        }

        public static void Test()
        {
            TestClass c = new TestClass();
            c.IsThisOK = IsThisOK("Hello");            
        }
    }

4 个答案:

答案 0 :(得分:3)

您正在尝试定义具有相同名称的属性和方法。虽然您可以使用多个方法相互覆盖(使用不同的参数列表),但您不能拥有共享相同名称的属性和方法

答案 1 :(得分:0)

因为您无法为函数和Property提供相同的名称。 你不能用属性重载函数。 您可以这样使用它:

 class TestClass

{
    public bool IsThisOK { get; set; }

    public static bool isThisOK(string str)
    {
        return true;
    }

    public static void Test()
    {
        TestClass c = new TestClass();
        c.IsThisOK = isThisOK("Hello");
    }

}

答案 2 :(得分:0)

你已经在第3行和第5行声明了IsThisOK两次(属性和静态函数)。

试着想象一下编译器怎么能弄清楚你以后会提到哪个?

答案 3 :(得分:0)

正如其他人指出的那样,你不能拥有同名的方法和属性。

但是,如果您愿意,可以使用扩展方法或多或少地解决此问题:

static class TestClassExtension
{
    public static bool IsThisOK(this TestClass, string str)
    {
        return true;
    }
}

class TestClass
{
    public bool IsThisOK { get; set; }

    public static void Test()
    {
        TestClass c = new TestClass();
        c.IsThisOK = this.IsThisOK("Hello");
    }
}