抽象方法声明 - virtual?
在 MSDN 上,我发现在抽象方法声明中使用“virtual”修饰符是错误的。 我的一位同事,应该是非常有经验的开发人员,但在他的代码中使用了这个:
public abstract class BusinessObject
{
public virtual void Render(){}
public virtual void Update(){}
}
它是否正确?
On MSDN I have found that it is a error to use "virtual" modifier in an abstract method declaration.
One of my colleagues, who should be pretty experienced developer, though uses this in his code:
public abstract class BusinessObject
{
public virtual void Render(){}
public virtual void Update(){}
}
Also it correct or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果抽象类提供了一个可选点,继承的类可以在其中改变行为,那么这是有意义的。
因此,通过这种方式,继承的类将不会被迫实现它,但如果需要的话它们可以实现。
通常此方法由抽象类调用:
这里将
OnAddedFoo
作为virtual
而不是abstract
是有意义的。It can make sense if the abstract class is providing an optional point where inherited classes can change the behaviour.
So this way the inherited classes will not be forced to implement it but they can if they need to.
Usually this method is called by the abstract class:
Here it makes sense to have
OnAddedFoo
asvirtual
and notabstract
.我猜 MSDN 的意思是你不能在一个方法上同时使用
virtual
和abstract
修饰符。您可以这样做
,这意味着继承类可以重写此方法。
或者您可以这样做
,这意味着继承类必须重写此方法。
I guess the MSDN means you can't use the
virtual
andabstract
modifier on a method at the same time.You can either do
which means that an inheriting class can override this method.
Or you can do
which means that an inheriting class must override this method.
这些不是抽象方法,它们是空的默认方法。不同之处在于您不必覆盖它们(如果不这样做,什么也不会发生)。
查看它们的格式可能会帮助您理解:
Those aren't abstract methods, they're empty default ones. The difference is you don't HAVE to override them (if you don't, nothing will happen).
It might help your understanding to see them formatted like:
你可能参考了这句话
这意味着您不能在方法声明中使用 this 方法不能同时是虚拟和抽象的。
因此,您提供的用法很好,因为该类是抽象的,这意味着您可以拥有一些抽象方法(没有必须由子类实现的实现)和虚拟方法(具有可以在子类中重写的实现)班级)。
You probably refer to this sentence
This mean that you can not use this in method declaration a method can't be at the same time virtual and abstract.
So the usage that you have presented is fine, because the class is abstract this mean that you can have there some abstract methods (with out implementation that have to be implemented by child class) and virtual method (with implementation that can be override in child class).
以下代码意味着您必须在继承类中验证此方法,并且您不能在抽象方法主体中放置一些逻辑:
但是如果您声明虚拟方法,您可以在其中放置一些逻辑并且可以 覆盖
Follwing code means that you must ovveride this method in inherited class and you can't put some logic in abstract method body:
But if you declare virtual method you can put some logic inside it and can ovveride