“as”会启用多态性吗?将继承的类传递给采用基类启用多态性的方法?
首先,我将使用virtual
和override
,
例如,基类A有方法A.do()
,继承类B有< code>B.do() 覆盖 A 的。
如果我调用(B as A).do()
,它会执行哪个do()
?
或者,如果有一个方法 void mymethod(A a) {a.do()}
,现在我通过 B b 调用它; mymethod(b)
,它会执行b.do()
吗?
Fist of all, I will use virtual
and override
for example, base class A has method A.do()
, inherited class B has B.do()
which overrides A's.
if I call (B as A).do()
, which do()
would it execute?
or, if there is a method void mymethod(A a) {a.do()}
, now I call it by B b; mymethod(b)
, would it execute b.do()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最顶层的重写方法总是会被调用,即
b.Do()
或(b as A).Do()
或((A)b) .Do()
将调用B.Do()
。如果子类重写它,我不知道如何从子类调用基方法。
The most top override method always will be called, i.e.
b.Do()
or(b as A).Do()
or((A)b).Do()
will callB.Do()
.I don't know a way how to call a base method from child class if child class overrides it.
输出:
Output:
这完全取决于 do() 方法是否被声明为虚拟方法。如果它不是虚拟的,则调用 A.do()。如果它是虚拟的,则调用 B.do()。 virtual 关键字启用了多态性,并允许调用独立于引用类型的方法。
C# 中没有任何机制允许从 B 对象引用直接调用虚拟 A.do() 方法。唯一的例外是在类 B 的实例方法中使用 base.do()。
It entirely depends on whether the do() method was declared virtual or not. If it is not virtual then A.do() is called. If it is virtual then B.do() is called. It is the virtual keyword that enables polymorphism and allows calling a method independent of the type of the reference.
There is no mechanism in C# that allows directly calling a virtual A.do() method from a B object reference. The only exception is using base.do() inside an instance method of class B.
编译器警告隐藏不覆盖:
这是因为您没有重写任何内容,而只是隐藏 A 的方法。
但是
在方法被重写时调用 B 两次。
compiler warns for hiding not overriding:
that is since you are not overriding anything, but simply hiding the method from A.
however
calls B twice, when method is overridden.