基于什么逻辑原因,virtual 和 new 修饰符在继承和多态问题上会产生不同的结果?

发布于 2024-07-26 05:12:25 字数 120 浏览 8 评论 0原文

我知道,当我们自己的基类中有一个虚函数,然后通过在派生类中重写它并在变量声明时考虑强制转换,与在派生类中使用 new 修饰符相比,我们会得到不同的结果。 但为什么? 这是否有任何逻辑上的理由,或者我们必须毫无理由地学习它?

I know that when we have a virtual function in our own base class, then by overriding it in a derived class and considering casting when variable declaration, we have different result with comparison to using new modifier in the derived class. but why? Is there any logical reason for that or we have to learn it without any reason?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

夜吻♂芭芘 2024-08-02 05:12:25

我假设您指的是 C#。

基本上,您使用 new当子类方法与超类方法无关时使用修饰符。 它们共享名称,但没有共享的多态行为。 当您以多态方式重新定义名称时,这称为覆盖。

I assume you are referring to C#.

Basically, you use the new modifier when the subclass method has nothing to do with the superclass method. They share the name, but there is no shared polymorphic behavior. When you are polymorphically redefining the name, that is called overriding.

满栀 2024-08-02 05:12:25

我建议不要使用 new 运算符,而是为该方法选择不同的名称。

Instead of using the new operator I would recommend choosing a different name for the method.

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