C#重写关键字

发布于 2024-09-30 00:43:35 字数 184 浏览 9 评论 0原文

我想知道如果我没有在派生类方法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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我早已燃尽 2024-10-07 00:43:35

首先,您将收到编译时错误,因为 virtual 成员不能是私有的,正如 A.m1 所写的那样。

其次,修复此问题后,您将收到一条编译时警告,指出 B.m1 隐藏了继承的成员 A.m1

第三,如果您执行以下操作:

A a = new B();
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 which A.m1 is as written.

Second, once you fix this, you'll get a compile-time warning that B.m1 hides the inherited member A.m1.

Third, if you do something like this:

A a = new B();
a.m1();

This will invoke A.m1 whereas if you insert override into the definition of B.m1 then the above will invoke B.m1. However, if you insert new into the definition of B.m1 then the above will still invoke A.m1 but it will omit the compile-time warning.

巾帼英雄 2024-10-07 00:43:35

据我所知,如果没有覆盖,编译器会发出警告。在这种情况下,该方法被视为具有修饰符 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 modifier new.

南城追梦 2024-10-07 00:43:35

当您编译时,它会向您发出警告,指出 B.m1() 隐藏了继承的成员 A.m1()

如果您希望打破继承链,则应该使用 new 关键字,或者使用 override 来获得虚拟行为。

When you compile it will give you a warning saying that B.m1() hides inherited member A.m1().

You should use the new keyword if you wish to break the inheritance chain, or use override to get your virtual behavior.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文