[英]Are abstract methods virtual?
Am I correct that declaring a method abstract
automatically makes it virtual? 我是否正确声明一个方法abstract
自动使其成为虚拟?
That is, in subclasses I can override it many times and at runtime, the method corresponding to the runtime type of the object will be called? 也就是说,在子类中,我可以多次覆盖它,并且在运行时,将调用与对象的运行时类型相对应的方法?
Is it possible to declare an abstract non-virtual method? 是否可以声明一个抽象的非虚方法? That is, the method which must be implemented in a non-abstract subclass and can not be overridden? 也就是说,必须在非抽象子类中实现并且不能被覆盖的方法?
Yes, abstract methods are virtual by definition; 是的, 抽象方法是虚拟的; they must be overridable in order to actually be overridden by subclasses: 它们必须是可覆盖的才能实际被子类覆盖:
When an instance method declaration includes an
abstract
modifier, that method is said to be an abstract method. 当实例方法声明包含一个abstract
修饰符时,该方法被称为抽象方法。 Although an abstract method is implicitly also a virtual method , it cannot have the modifiervirtual
. 虽然抽象方法也隐式也是虚方法 ,但它不能具有virtual
修饰符。
Conversely you can't declare an abstract non-virtual method, because if you could, you would have a method that can't be implemented and thus can never be called, making it rather useless. 相反,你不能声明一个抽象的非虚方法,因为如果可以的话,你会有一个无法实现的方法,因此永远不会被调用,这使得它变得毫无用处。
However, if you want to have a class implement an abstract method but not allow any of its subclasses to modify its implementation, that's where sealed
comes in. An example: 但是,如果你想让一个类实现一个抽象方法但不允许它的任何子类修改它的实现,那就是sealed
进来的地方。例如:
abstract public class AbstractClass
{
abstract public void DoSomething();
}
public class BaseClass : AbstractClass
{
public sealed override void DoSomething()
{
Console.WriteLine("Did something");
}
}
Notice that while the abstract method is (implicitly) virtual, the implementation in the concrete base class is non-virtual (because of the sealed
keyword). 请注意,虽然抽象方法(隐式)是虚拟的,但具体基类中的实现是非虚拟的(因为使用了sealed
关键字)。
Yes, they are virtual. 是的,他们是虚拟的。 Otherwise you would have no way to write implementation for them. 否则你将无法为它们编写实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.