
在 Visual Basic 中,抽象类用 MustInherit 关键字表示。在 C# 中,则使用 abstract 修饰符。任何所谓不变的方法都可以编码至基类中,但在 Visual Basic 中,任何要实现的方法都用 MustOverride 修饰符标记。在 C# 中,这些方法标记为 abstract。下例显示了一个抽象类:
'' Visual Basic
Public MustInherit Class WashingMachine
Sub New()
'' Code to instantiate the class goes here.
End sub
Public MustOverride Sub Wash
Public MustOverride Sub Rinse (loadSize as Integer)
Public MustOverride Function Spin (speed as Integer) as Long
End Class
// C#
abstract class WashingMachine
{
public WashingMachine()
{
// Code to initialize the class goes here.
}
abstract public void Wash();
abstract public void Rinse(int loadSize);
abstract public long Spin(int speed);
}
在上面的示例中,用一个已实现的方法和三个未实现的方法声明抽象类。从该类继承的类必须实现 Wash、Rinse 和 Spin 方法。下例显示了该类实现的可能形式:
'' Visual Basic
Public Class MyWashingMachine
Inherits WashingMachine
Public Overrides Sub Wash()
'' Wash code goes here
End Sub
Public Overrides Sub Rinse (loadSize as Integer)
'' Rinse code goes here
End Sub
Public Overrides Function Spin (speed as Integer) as Long
'' Spin code goes here
End Sub
End Class
// C#
class MyWashingMachine : WashingMachine
{
public MyWashingMachine()
{
// Initialization code goes here.
}
override public void Wash()
{
// Wash code goes here.
}
override public void Rinse(int loadSize)
{
// Rinse code goes here.
}
override public long Spin(int speed)
{
// Spin code goes here.
}
}
在实现抽象类时,必须实现该类中的每一个抽象 (MustOverride) 方法,而每个已实现的方法必须和抽象类中指定的方法一样,接收相同数目和类型的参数,具有同样的返回值。