如何避免向下转换为接口类?

Mue*_*uel 4 excel inheritance vba casting excel-vba

我正在使用Excel VBA(Excel 2010),并且在尝试使用继承时遇到了问题.基本上,我有一个接口MyInterface和一个实现类MyImplementation.在VBA代码中,当我引用一个Dim类型时MyInterface,我只能访问在该接口上定义的成员 - 这是预期的.当我引用一个Dim类型时MyImplementation,我无法访问它实现的接口上定义的成员 - 不是预期的.

为什么我不能直接在实现类上调用interface属性?

MyInterface的

Option Explicit

Public Property Get Text() As String
End Property
Run Code Online (Sandbox Code Playgroud)

MyImplementation

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

主要问题是如何避免向下投射?

注意 - 上面的例子是有意设计的.我意识到直接引用实现类通常是不好的做法.

Joe*_*Joe 6

当我引用MyImplementation类型的Dim时,我无法访问它实现的接口上定义的成员 - 不是预期的.

解决方案是改变您的期望.这就是VBA中的工作方式:VBA类实现COM接口(例如IUnknown)而不公开它们.

如果要从类中公开接口的成员,则必须明确地这样做:

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

Public Property Get Text() As String
    Text = MyInterface_Text 
End Property
Run Code Online (Sandbox Code Playgroud)