我正在使用VB.Net。vb.net class MustInherit接口
我有幾個X
對象。他們每個人都需要有Y
功能,所以我需要選擇Interface
或MustInherit
。我還需要爲每個對象都有一個Z
函數完全相同。該功能僅用於對象的抽象/實現方法,如用於該類對象的打印輸出。
這樣做的最好方法是什麼?
我正在使用VB.Net。vb.net class MustInherit接口
我有幾個X
對象。他們每個人都需要有Y
功能,所以我需要選擇Interface
或MustInherit
。我還需要爲每個對象都有一個Z
函數完全相同。該功能僅用於對象的抽象/實現方法,如用於該類對象的打印輸出。
這樣做的最好方法是什麼?
我只使用一個接口,如果你期望有類實現Y
但不需要Z
函數。
因爲所有的子類都需要Z
函數,所以我會抽象出來。如果Z
只在班級內使用,請將其標記爲Protected
,以便它僅對子類可見。
MustInherit Class BaseX
Public MustOverride Sub Y();
Protected Sub Z()
' TODO: Implement common version of Z.
End Sub
End Class
Class FirstX Inherits BaseX
Public Overrides Sub Y()
' TODO: Implement first version of Y.
' Call Z() as required.
End Sub
End Class
Class SecondX Inherits MyBaseClass
Public Overrides Sub Y()
' TODO: Implement second version of Y.
' Call Z() as required.
End Sub
End Class
注:我希望我的VB是正確的。我沒有安裝它,所以我無法驗證我的語法。
不太明白你的問題。如果你想要一個很好的答案,你可能想讓你的問題更清楚。 根據我的理解,您想知道如何使用繼承來創建兩個繼承相同MustInherit類的+對象,並使用不同的實現執行類似的操作。 我不明白你的X函數和Z函數之間的區別。
Public MustInherit Class theBase
Public MustOverride Sub ZPrint()
End Class
Public Class a
Inherits theBase
Public Overrides Sub ZPrint()
' the "a" way to print
End Sub
End Class
Public Class b
Inherits theBase
Public Overrides Sub ZPrint()
' the "b" way to print
End Sub
End Class
Public Class theClass
Public Sub run()
Dim myA As theBase
Dim myB As theBase
myA = New a
myB = New b
myA.ZPrint()
myB.ZPrint()
End Sub
End Class
創建該類的一個實例並執行run()方法。
我會檢查,但整體看起來不錯。似乎回答我的問題。 – forX