为什么我会收到警告CS0108有关属性从基类中隐藏方法的警告 [英] Why do I get warning CS0108 about a property hiding a method from a base class
问题描述
鉴于以下类,C#编译器会向我发出此警告:-
Given the following classes the C# compiler gives me this warning:-
CS0108'B.Example'隐藏继承的成员'A.Example(string)'.如果打算隐藏,请使用new关键字".
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);
}
}
我得到以下输出
A
B
那是我的期望.
在我看来,什么都没有被隐藏.确实如果类B实际上包含像这样的简单方法重载,那么我不会收到任何等效警告.
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?
推荐答案
您的第一个示例类B将具有示例"属性,因此隐藏了方法Example(string),编译器会要求您指定新的关键字来进行说明您的意图:
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;
}
在第二个示例中,Example(string/int)的两个方法实现都将可见.因此,B类实现不会隐藏它:
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);
}
这篇关于为什么我会收到警告CS0108有关属性从基类中隐藏方法的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!