基于什么逻辑原因,virtual 和 new 修饰符在继承和多态问题上会产生不同的结果?
我知道,当我们自己的基类中有一个虚函数,然后通过在派生类中重写它并在变量声明时考虑强制转换,与在派生类中使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设您指的是 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.我建议不要使用 new 运算符,而是为该方法选择不同的名称。
Instead of using the new operator I would recommend choosing a different name for the method.