【发布时间】:2012-10-22 21:27:15
【问题描述】:
我在 VB.Net 中工作。
我有几个X 对象。他们每个人都需要有Y功能,所以我需要选择Interface或MustInherit。对于每个对象,我还需要一个完全相同的Z 函数。此函数仅由对象的抽象/实现方法使用,例如此类对象的打印输出。
最好的方法是什么?
【问题讨论】:
我在 VB.Net 中工作。
我有几个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
创建 class 的实例并执行 run() 方法。
【讨论】: