比较:接口方法、虚方法、抽象方法
它们各自的优点和缺点是什么?
- 接口方法
- 虚方法
- 抽象方法
什么时候应该选择什么?做出这一决定时应牢记哪些要点?
What are the advantages and disadvantages of each of these?
- interface methods
- virtual methods
- abstract methods
When one should choose what? What are the points one should keep in mind when making this decision?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
虚拟和抽象几乎是一样的。虚方法在基类中有一个实现,可以选择重写,而抽象方法则没有,并且必须在子类中重写。否则它们是相同的。在它们之间进行选择取决于具体情况。如果您有基本实现,则可以使用虚拟。如果你不这样做,并且你需要每个后代自己实现它,那么你选择抽象。
接口方法是在类实现的接口中声明的方法的实现。这与其他两个完全无关。我认为一个方法既可以是虚拟的,也可以是接口的。接口的优点是您声明一个可以由两个完全不同的类实现的接口(废话)。这样,您就可以在两个不同的类上运行相同的代码,只要您要调用的方法是在它们共享的接口中声明的。
Virtual and abstract are almost the same. A virtual method has an implementation in the base class that can optionally be overridden, while an abstract method hasn't and must be overridden in a child class. Otherwise they are the same. Choosing between them depends on the situation. If you got a base implementation, you use virtual. If you don't, and you need every descendant to implement it for itself, you choose abstract.
Interface methods are implementations of a method that is declared in an interface that the class implements. This is quite unrelated to the other two. I think a method can be both virtual and interface. The advantage of interfaces is that you declare one interface (duh) that can be implemented by two totally different classes. That way, you can run the same code on two different classes, as long as the methods you'd like to call are declared in an interface they share.