Why do I get warning CS0108 about a property hiding a method from a base class [duplicate]

空扰寡人 提交于 2021-01-28 02:00:14

问题


Given the following classes the C# compiler gives me this warning:-

CS0108 "'B.Example' hides inherited member 'A.Example(string)'. Use the new keyword if hiding was intended".

class A
{
    public string Example(string something)
    {
        return something;
    }
}

class B : A
{
    public string Example => "B";
}

If use the classes running this code

class Program
{
    static void Main(string[] args)
    {
        B b = new B();
        Console.WriteLine(b.Example("A"));
        Console.WriteLine(b.Example);
    }
}

I get the following output

A
B

Which is what I would expect.

It doesn't seem to me that anything is being hidden at all. Indeed if class B actually contains a simple method overload like this then I get no equivalent warning.

class B : A
{
    public string Example(int another) => "B";
}

Is there something special about a property that makes that compiler warning valid or is this a case of a false positive in the compiler?


回答1:


Your first example class B will have a Property "Example", thus hiding the method Example(string) and the compiler ask you to specify the new keyword to clarify your intentions:

class B
{
    public string Example;
}

In your second example both method implementations of Example(string/int) will be visible. So no hiding by the class B implementation:

class B
{
    public string Example(string something);
    public string Example(int another);
}


来源:https://stackoverflow.com/questions/48299497/why-do-i-get-warning-cs0108-about-a-property-hiding-a-method-from-a-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!