共用方式為


MustInherit (Visual Basic)

指定類別只能當做基類使用,而且您無法直接從它建立物件。

備註

基類(也稱為抽象類)的目的是定義衍生自該基類的所有類別通用的功能。 這樣會儲存衍生類別,而不需要重新定義通用元素。 在某些情況下,這個常見功能不夠完整,無法建立可使用的物件,而且每個衍生類別都會定義遺漏的功能。 在這種情況下,您希望取用的程式代碼只從衍生類別建立物件。 您會在 MustInherit 基類上使用 來強制執行此作業。

類別的另一個 MustInherit 用法是將變數限製為一組相關的類別。 您可以定義基類,並從中衍生所有相關類別。 基類不需要提供所有衍生類別通用的任何功能,但它可作為將值指派給變數的篩選條件。 如果您的取用程式代碼將變數宣告為基類,Visual Basic 可讓您只將其中一個衍生類別的物件指派給該變數。

.NET Framework 會定義數個 MustInherit 類別,其中包括 ArrayEnumValueTypeValueType 是限制變數的基類範例。 所有實值型別都衍生自 ValueType。 如果您將變數宣告為 ValueType,則只能將實值型別指派給該變數。

規則

  • 宣告內容。 MustInherit您只能在語句中使用Class

  • 合併的修飾元。 您無法在相同的宣告中一MustInherit起指定 NotInheritable

範例

下列範例說明強制繼承和強制覆寫。 基類 shape 會定義變數 acrossLine。 類別 circlesquare 衍生自 shape。 它們會繼承 的定義 acrossLine,但必須定義 函式, area 因為每種圖形的計算都不同。

Public MustInherit Class shape
    Public acrossLine As Double
    Public MustOverride Function area() As Double
End Class
Public Class circle : Inherits shape
    Public Overrides Function area() As Double
        Return Math.PI * acrossLine
    End Function
End Class
Public Class square : Inherits shape
    Public Overrides Function area() As Double
        Return acrossLine * acrossLine
    End Function
End Class
Public Class consumeShapes
    Public Sub makeShapes()
        Dim shape1, shape2 As shape
        shape1 = New circle
        shape2 = New square
    End Sub
End Class

您可以宣告 shape1shape2 為類型 shape。 不過,您無法從 shape 建立物件,因為它缺少 函式的功能 area ,而且標示 MustInherit為 。

因為它們宣告為 shape,所以變數 shape1shape2 會限制為衍生類別 circlesquare中的物件。 Visual Basic 不允許您將任何其他物件指派給這些變數,這可提供您高階的類型安全性。

用法

MustInherit修飾詞可用於此內容:

類別陳述

另請參閱