jjzjj

c# - 如果我不注意警告 "hides inherited member. To make the current member override that implementation...."怎么办

coder 2023-07-10 原文

这可能是一个很好的观点,但它涉及编译器发出的警告,如果您执行以下操作:

class A
{
    public virtual void F() { }
}
class B : A
{
    public void F() { }
}

然后你会得到警告:

'EomApp1.B.F()' hides inherited member 'EomApp1.A.F()'.<br/> To make the current member override that implementation, add the override keyword. Otherwise use the new keyword.

问题:如果我不采取任何措施,实际警告我的警告是什么?如果我添加“new”关键字与不添加关键字,我的程序功能是否会有所不同?

(注意:我知道我可以很容易地测试这个,但我认为值得在这里问)

最佳答案

它不会做任何事情,但你在那里的方法 F() 也不是多态的。如果您开始使用基类引用,就会很容易在代码中出错,因此您会收到警告。当然它可以是你想要的,因此 new 关键字只是让它更明确

例如

B b1 = new B();
b1.F(); // will call B.F()

A b2 = new B();
b2.F(); // will call A.F()

现在,如果您使用 new 添加类 C,它的行为将与 B 相同。如果您使用 override 添加类 D,则 F 变为多态:

class C : A
{
    public new void F() { }
}

class D : A
{
    public override void F() { }
}

// Later

C c1 = new C();
c1.F(); // will call C.F()

A c2 = new C();
c2.F(); // will call A.F()

D d1 = new D();
d1.F(); // will call D.F()

A d2 = new D();
d2.F(); // will call D.F()

参见 this fiddle .

关于c# - 如果我不注意警告 "hides inherited member. To make the current member override that implementation...."怎么办,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5933045/

有关c# - 如果我不注意警告 "hides inherited member. To make the current member override that implementation...."怎么办的更多相关文章

随机推荐