您的位置:首页 > 其它

在.NET 应用程序设计中如何选择Class, Abstract Class and Interface

2015-03-06 18:30 477 查看
关键字:

Type– 类型

Class - 类

Abstract - 抽象的

Interface - 接口

Member - 成员

Method - 方法

Property - 属性

预备知识:在阅读本文时,您应当了解.NET编程的基本知识并且已经掌握Class, Abstract Class 和 Interface全部知识。这里我仅简单介绍一下他们的基本知识。本文的例子由C#编写。期望您对C#编程有一定的了解。

正文:

我们无法创建一个Abstract Class或Interface的实例(INSTANCE)。让我们从Abstract Class和Interface的定义来看他们的不同。Abstract Class可以包含Abstract Methods 和 Abstract Properties, 也可以包含其他的Members,象正常的Class一样。而Interface只能包含Abstract Methods和Properties(属性)。Interface中的所有Methods和Properties不需要加Abstract和 Public关键字,因为这两个关键字在Interface中是默认的。举例如下:

//Abstarct Class
public abstract class Vehicles
{
private int noOfWheel;
private string color;
public abstract string Engine
{
get;
set;
}
public abstract void Accelerator();
}

//Interface
public interface Vehicles
{
string Engine
{
get;
set;
}
void Accelerator();
}


通常来讲,在设计时优先考虑使用Class或Abstract Class而不是Interface。Interface的主要缺点是灵活性比较差。一旦你定义好了Interface,那么它的Members就固定 了。如果你要对已经发布的程序添加新的Method,就会破坏你已经的实现该接口的Type(Class,Struct等)。因为你必须在你已有的 Type中实现新的方法,否则你的程序将无法通过编译。

例如类Car和Train实现了接口Vehicles. 现在我们要给接口Vehicles再加一个方法Brake(). 如果我们现在编译类Car和Train,编译器将报错。

public interface Vehicles
{
…
//新添加的方法
void Brake();
}
要修复这个错误,我们不得不在类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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐