我正在使用Excel VBA(Excel 2010),在尝试使用继承时遇到了问题。基本上,我有一个接口
主要问题是如何避免强制类型转换?
注意 - 上面的例子是故意编造的。我意识到直接引用实现类通常是不好的做法。
MyInterface
和一个实现类MyImplementation
。在VBA代码中,当我引用类型为MyInterface
的Dim
时,我只能访问该接口上定义的成员 - 这是预期的。当我引用类型为MyImplementation
的Dim
时,我无法访问它实现的接口上定义的成员 - 这是不可预期的。
为什么我不能直接在实现类上调用接口属性呢?
MyInterface
Option Explicit
Public Property Get Text() As String
End Property
我的实现
Option Explicit
Implements MyInterface
'The implementation of the interface method'
Private Property Get MyInterface_Text() As String
MyInterface_Text = "Some Text"
End Property
Public Property Get MoreText() As String
MoreText = "Yes, some more text!"
End Property
MainModule - 使用示例
Function Stuff()
Dim impl As New MyImplementation
Dim myInt As MyInterface: Set myInt = impl
'The following line is fine - displays "Yes, some more text!"
MsgBox impl.MoreText
'This is also fine - displays "Some text"
MsgBox DownCast(impl).Text
'This is also fine - displays "Some text"
MsgBox myInt.Text
'This is *not* fine - why??
MsgBox impl.Text
End Function
Function DownCast(ByRef interface As MyInterface) As MyInterface
Set DownCast = interface
End Function
主要问题是如何避免强制类型转换?
注意 - 上面的例子是故意编造的。我意识到直接引用实现类通常是不好的做法。
MyImplementation
的客户端代码,这个解决方案很好,但对于所有实现MyInterface
的类来说,它并不适用。如果我的接口有10个属性和10个实现类,那么我就必须编写100个方法!从长远来看,这似乎难以维护。无论如何,你说得对:我需要改变我的期望!感谢你的回答 - 已接受! - Muel