【发布时间】:2014-07-09 10:48:59
【问题描述】:
我正在使用 Excel VBA (Excel 2010),但在尝试使用继承时遇到了问题。基本上,我有一个接口MyInterface 和一个实现类MyImplementation。在 VBA 代码中,当我引用 MyInterface 类型的 Dim 时,我只能访问在该接口上定义的成员 - 这是预期的。当我引用 MyImplementation 类型的 Dim 时,我无法访问在它实现的接口上定义的成员 - 不是预期的。
为什么不能在实现类上直接调用接口属性?
我的界面
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
主要问题是如何避免向下转换?
注意 - 上面的示例是故意设计的。我意识到直接引用实现类通常是不好的做法。
【问题讨论】:
标签: vba excel inheritance casting