我有两个独立的类(A = BevelButtom的子类,B = PushButton的子类)。 A和B都以完全相同的方式实现了许多相同的方法。由于两个子类的超类都不同,并且因为RB不支持多重继承,所以我只能将这些方法绑定在一起就是定义一个类接口,让两个子类实现接口,然后在每个子类中复制/粘贴方法体。
这会冒犯我的感情。 RB中有没有办法在其他地方提取这种通用逻辑?
谢谢!
答案 0 :(得分:3)
使用模块方法中的Extends语法扩展类接口。您仍然需要使用类接口,但这样所有公共代码都可以放在模块中,而不是跨多个类重复。
Interface FooInterface
Sub Foo()
End Interface
Class Foo
Implements FooInterface
Sub Foo()
MsgBox("Foo!")
End Sub
End Class
Class Bar
Implements FooInterface
Sub Foo()
MsgBox("Bar!")
End Sub
End Class
Module FooExtensions
Sub Foobar(Extends FooImplementor As FooInterface)
MsgBox("Foobar!")
End Sub
End Module
上面的FooBar方法将被调用为实现FooInterface类接口的任何类的类方法:
Dim myfoo As FooInterface = New Bar
myfoo.Foobar()
请注意,当编译器决定给定的类是否满足接口时,扩展方法不计算。
然而,这可能不可行,因为扩展方法只能访问接口而不是实际的类。
或者,您可以扩展RectControl
类,但这包括所有桌面控件,而不仅仅是PushButton和BevelButton。
第三种选择可能是专门使用BevelButton类。
答案 1 :(得分:2)
使用接口似乎是正确的方法,但不是将方法体复制到每个子类,我认为使用公共代码创建一个新类(比如CommonButtonStuff)更有意义。然后你可以用实现的方法调用它:
CommonButtonInterface
Sub Method1
Class CommonButtonHandler
Sub DoMethod1
MsgBox("Do it!")
End Sub
Class A Inherits From PushButton, Implements CommonButtonInterface
Private Property mCommonStuff As CommonButtonHandler
Sub Constructor
mCommonStuff = New CommonButtonHandler
End Sub
Sub Method1
mCommonStuff.DoMethod1
End Sub
Class B Inherits From BevelButton, Implements CommonButtonInterface
Private Property mCommonStuff As CommonButtonHandler
Sub Constructor
mCommonStuff = New CommonButtonHandler
End Sub
Sub Method1
mCommonStuff.DoMethod1
End Sub