简体   繁体   English

抽象还是虚拟方法?

[英]Abstract or virtual method?

Whats recommended in an abstract class? 在抽象课中推荐什么?

Have a virtual method returning null, or have an abstract method? 让虚方法返回null,或者有一个抽象方法?

It is convenient and easy to have them returning null, as I don't have to do anything inheriting from the abstract class. 让它们返回null是方便和容易的,因为我不必做任何继承自抽象类的事情。 But still, returning null is somewhat hard to understand if it is by purpose, error, or by design.... 但是,如果出于目的,错误或设计的原因,返回null有点难以理解。

Are there any clear recommendations for this? 对此有明确的建议吗?

If returning null is a sensible and sane thing to do as a default behaviour (with supporting documentation), then perhaps virtual is fine. 如果返回null是一个明智且理智的事情,作为默认行为(使用支持文档),那么也许virtual就好了。 Likewise, if you can create a sensible default but just want to offer extensibility: virtual . 同样,如果您可以创建合理的默认值,但只想提供可扩展性: virtual

If the (concrete) class cannot function without a non-default implementation, then make it abstract . 如果(具体)类在没有非默认实现的情况下无法运行 ,那么将其abstract The casebook scenario here is Stream : without a sane implementation where would the bytes come from? 这里的案例手册是Stream :没有一个理智的实现,字节来自哪里? (/go to). (/去)。

如果我要求派生类提供功能,我有一个抽象方法,如果我不那么烦恼,我有一个返回null(或做一些默认操作)的虚方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM