知识大全 .NET中Class, Abstract and Interfa选择[2]
Posted 类型
篇首语:人非生而知之,孰能无惑?惑而不从师,其为惑也,终不解矣。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 .NET中Class, Abstract and Interfa选择[2]相关的知识,希望对你有一定的参考价值。
.NET中Class, Abstract and Interfa选择[2] 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!
要修复这个错误 我们不得不在类Car和Train中实现方法Brake() 示范代码如下
public class Car : Vehicles … public void Brake() System Console WriteLine( Stop your car ); public class Train : Vehicles … public void Brake() System Console WriteLine( Stop your train );
如果我们使用抽象类或正常类Vehicles 我们仅仅需要在类Vehicles中添加Brake()方法并且实现这个方法 然后我们根据具体需要来决定是否要覆蓋类Car 或Train中的Brake()方法
public abstract class Vehicles … //新添加的方法 无需在它的子类中覆蓋这个方法 public void Brake() System Console WriteLine( Stop your vehicles );
Class则可以提供更好的灵活性 你可以给Class添加任何Members 只要添加的不是Abstract Method即可(也就是说你要提供一个有具体实现的方法) 这样就不会影响从该Class继承的类 已有代码无需做任何改变
设计原则
优先考虑使用Class或Abstract Class而不是Interface
使用Abstract Class代替Interface来降低Class继承层次之间的耦合关系
使用Interface 如果你需要给一个值类型实现(Value Type 象STRUCT就是值类型)多态继承(Polymorphic Hierarchy) (值类型除了从Interface继承以外 不能从其他Type继承)
在需要多重继承的情况下 可以考虑使用Interface
参考目录 Microsoft NET Development Series Framework Design Guidelines
cha138/Article/program/net/201311/15659相关参考