继承修饰符(关于属性和方法)

重写

允许在派生类中重写类中的属性或方法。

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