[英]Calling an abstract method in a non-abstract method within an abstract class
I have an abstract class in C#: 我在C#中有一个抽象类:
public void activation()
{
activated = true;
on_Activation();
}
protected abstract void on_Activation();
Scenario: 场景:
Assume I've made a child of the abstract class and made an implementation of the method, on_Activation()
. 假设我已经成为抽象类的子代,并实现了
on_Activation()
方法的实现。
Questions: 问题:
Activation()
in the child class? Activation()
时会发生什么? on_Activation()
use the implementation of on_Activation
in the child class? on_Activation()
使用的实施on_Activation
在子类? Yes. 是。 It's a virtual method (implicitly, because it's abstract) so its "most overridden" version will be called.
这是一个虚拟方法(隐式,因为它是抽象的),因此将调用其“最被覆盖”的版本。 The fact that the call originates in a method defined on the base class makes no difference.
调用源自基类上定义的方法的事实没有区别。
Yes. 是。 And you have just discovered polymorphism .
您刚刚发现了多态性 。 Polymorphism means that you just call a method like
on_Activation
on an object (whether the current object called this
, or any other object) and you do not need to specify which version of on_Activation
you mean. 多态意味着您只需要在一个对象(无论当前对象名为
this
还是任何其他对象)上调用诸如on_Activation
类的方法,而无需指定您所指的on_Activation
版本。 It is the actual type of the object at runtime that decides which version of on_Activation
actually gets called. 它是运行时对象的实际类型 ,它决定实际调用哪个版本的
on_Activation
。
As Thomas noted, methods which behave this way are called virtual . 正如Thomas所指出的那样,以这种方式运行的方法称为virtual 。 All abstract methods are virtual in C#.
所有抽象方法在C#中都是虚拟的。 So a virtual method is a name, a symbol, that can polymorphically refer to different things (different method bodies ) at runtime.
因此,虚拟方法是一个名称,符号,可以在运行时多态地引用不同的事物(不同的方法主体 )。
If you are curious and want to know what kind of magic is involved, you can check the details at Virtual method table . 如果您好奇并且想知道涉及哪种魔术,则可以在“ 虚拟方法表”中查看详细信息。 Essentially every virtual method name like
on_Activation
is translated as an index like n
, that is the n
th virtual method of this class. 本质上,每个虚拟方法名称(如
on_Activation
都将转换为索引(如n
,即该类的第n
个虚拟方法。 Every non-abstract class provides a table in which all its virtual methods bodies are specified. 每个非抽象类都提供一个表,其中指定了其所有虚拟方法主体 。 So, a call to
on_Activation
on an object is translated as a call to the n
th entry in the virtual method table of the class of that object. 因此,
on_Activation
对象的on_Activation
的调用转换为对该对象类的虚拟方法表中的第n
个条目的调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.