如果我不注意“隐藏继承的成员"的警告怎么办.使当前成员覆盖该实现......" [英] What if I don't heed the warning "hides inherited member. To make the current member override that implementation...."

查看:34
本文介绍了如果我不注意“隐藏继承的成员"的警告怎么办.使当前成员覆盖该实现......"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is maybe a fine point, but it concerns the warning that the compiler issues if you do something like:

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

然后你会收到警告:

'EomApp1.B.F()'隐藏继承的成员'EomApp1.A.F()'.
要使当前成员覆盖该实现,请添加 override 关键字.否则使用 new 关键字.

问题:如果我什么都不做,实际警告我会发生什么警告?如果我添加new"关键字与不添加关键字,我的程序的功能是否会有所不同?

QUESTION: What is the warning actually warning me will happen if I do nothing about it? Will my program function differently if I add the 'new' keyword vs. if I do not?

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

(Note: I know I could test this easily enough but I figured it was worth asking here)

推荐答案

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

It will not do anything but the method you have there F() is also not polymorphic. It becomes very easy to make mistake in code if you started to use base class reference hence you are warned. Of course it can be what you want, hence the new keyword just make it more explicit

例如

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

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

现在,如果您将 C 类与 new 一起添加,它的行为将与 B 相同.如果你用 override 添加类 D,那么 F 就变成了多态的:

Now, if you add class C with new, it will behave the same as B. If you add class D with override, then F becomes polymorphic:

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()

参见这个小提琴.

这篇关于如果我不注意“隐藏继承的成员"的警告怎么办.使当前成员覆盖该实现......"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆