问题
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