C#重写关键字
我想知道如果我没有在派生类方法m1()
中的方法前面放置override
关键字,那么在此之前的默认值是什么,或者会不会抛出编译时错误?
class A { virtual void m1(){} }
class B: A { void m1(){} }
I want to know if i don't put override
key word before the method in derived class method m1()
, then what is the default value before this, or will it throw a compile time error?
class A { virtual void m1(){} }
class B: A { void m1(){} }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您将收到编译时错误,因为
virtual
成员不能是私有的,正如A.m1
所写的那样。其次,修复此问题后,您将收到一条编译时警告,指出
B.m1
隐藏了继承的成员A.m1
。第三,如果您执行以下操作:
这将调用
A.m1
而如果您将override
插入到B.m1
的定义中,则上面将调用B.m1
。但是,如果将new
插入到B.m1
的定义中,那么上面的代码仍然会调用A.m1
,但会省略编译 -时间警告。First, you'll get a compile-time error because
virtual
members can not be private whichA.m1
is as written.Second, once you fix this, you'll get a compile-time warning that
B.m1
hides the inherited memberA.m1
.Third, if you do something like this:
This will invoke
A.m1
whereas if you insertoverride
into the definition ofB.m1
then the above will invokeB.m1
. However, if you insertnew
into the definition ofB.m1
then the above will still invokeA.m1
but it will omit the compile-time warning.据我所知,如果没有覆盖,编译器会发出警告。在这种情况下,该方法被视为具有修饰符
new
。Without
override
the compiler issues a warning, as far as I can remember. In this case the method is treated as if it had modifiernew
.当您编译时,它会向您发出警告,指出
B.m1()
隐藏了继承的成员A.m1()
。如果您希望打破继承链,则应该使用 new 关键字,或者使用 override 来获得虚拟行为。
When you compile it will give you a warning saying that
B.m1()
hides inherited memberA.m1()
.You should use the new keyword if you wish to break the inheritance chain, or use override to get your virtual behavior.