繼承修飾符(關於屬性和方法)

重寫

允許在派生類中重寫類中的屬性或方法。

Public Class Person
    Public Overridable Sub DoSomething()
        Console.WriteLine("Person")
    End Sub
End Class

覆蓋

覆蓋基類中定義的 Overridable 屬性或方法。

Public Class Customer
    Inherits Person

    'Base Class must be Overridable
    Public Overrides Sub DoSomething()
        Console.WriteLine("Customer")
    End Sub
End Class

NotOverridable

防止在繼承類中重寫屬性或方法。預設行為。只能在覆蓋方法上宣告 ****

Public Class Person

    Public Overridable Sub DoSomething()
        Console.WriteLine("Person")
    End Sub

End Class

Public Class Customer
    Inherits Person

    Public NotOverridable Overrides Sub DoSomething()
        Console.WriteLine("Customer")
    End Sub

End Class

Public Class DetailedCustomer
    Inherits Customer

    'DoSomething can't be overridden
End Class

用法示例:

Dim p As New Person
p.DoSomething()

Dim c As New Customer
c.DoSomething()

Dim d As New DetailedCustomer
d.DoSomething()

輸出:

Person
Customer
Customer

MustOverride

要求派生類重寫屬性或方法。

必須在 MustInherit 類中宣告 MustOverride 方法**。**

Public MustInherit Class Person

    Public MustOverride Sub DoSomething()
    'No method definition here

End Class

Public Class Customer
    Inherits Person

    'DoSomething must be overridden
    Public Overrides Sub DoSomething()
        Console.WriteLine("Customer")
    End Sub

End Class

用法示例:

Dim c As New Customer
c.DoSomething()

輸出:

Customer