VBA:有类似抽象类的东西吗?

min*_*ins 12 excel vba abstract-class interface excel-vba

我正在使用一个接口来确保一些类似的类实现一些强制方法(子/函数).

例:

  • 接口I1声明M1和M2方法
  • C1和C2实现了I1,并且有自己的M1和M2版本.

C1和C2也需要完全相同的方法,例如方法SM1和SM2.

为了避免重复SM1和SM2,我想定义一个抽象类AC:

  • 实施I1
  • 定义SM1和SM2.

这将由C1和C2扩展

这个解决方案确实可以在Java中使用,但我找不到任何在VBA中执行相同操作的文档.(VB.Net似乎允许使用关键字MustInherit的抽象类.)

在VBA中是否可以确认?

GSe*_*erg 17

VBA中没有继承.

您可以定义接口,并可以使用Implements关键字在类中实现它.但是,如果您希望基类预先实现共享功能,则必须使用复制粘贴方法.

相关阅读:
如何在Excel VBA中使用Implements
如何使用与VB.NET类似的方式在VBA中的类对象模块之间使用比较方法?


dee*_*dee 13

您可以在VBA中实现半装饰器:-)模式.假设我们有一个基类和两个子类.如果在子类中使用Implements关键字,则会认为子类与基类具有相同的接口,同时在每个子类中声明基类的私有实例,并将调用从子类重定向到基类.

注:此处的基类是普通的类,你仍然可以创建它的实例(所以它不是真正的抽象类).

例:

' Standard module

Sub main()
    Dim a As New ChildA
    Dim b As New ChildB

    a.State = 2
    b.State = 5

    Debug.Print TypeOf a Is Base
    Debug.Print TypeOf b Is Base

    TestPolymorphic a
    TestPolymorphic b
End Sub

Private Sub TestPolymorphic(ByRef obj As Base)
    obj.Polymorphic
End Sub

' -----------------------------------------------

' Base class module

Private m_state As Byte

Public Event StateChanged(oldState As Byte, newState As Byte)

Public Property Get State() As Byte
    State = m_state
End Property

Public Property Let State(ByVal newState As Byte)
    Dim oldState As Byte
    oldState = m_state
    m_state = newState
    RaiseEvent StateChanged(oldState, newState)
End Property

Sub Polymorphic()
    Err.Raise 123, , "Implement in child class"
End Sub

Private Sub Class_Initialize()
    m_state = 1
End Sub

' -----------------------------------------------

' ChildA class module

Implements Base
Private WithEvents m_base As Base

Private Sub Class_Initialize()
    Set m_base = New Base
End Sub

Public Property Get State() As Byte
    State = Base_State
End Property

Public Property Let State(ByVal newState As Byte)
    Base_State = newState
End Property

Public Sub Polymorphic()
    Base_Polymorphic
End Sub

Private Property Get Base_State() As Byte
    Base_State = m_base.State
End Property

Private Property Let Base_State(ByVal newState As Byte)
    m_base.State = newState
End Property

Private Sub Base_Polymorphic()
    Debug.Print "In Child A ..."
End Sub

Private Sub m_base_StateChanged(oldState As Byte, newState As Byte)
    Debug.Print "State of 'Child A' instance has changed from " & oldState & " to " & newState
End Sub

Output:
' State of 'Child A' instance has changed from 1 to 2
' State of 'Child B' instance has changed from 1 to 5
' True
' True
' In Child A ...
' In Child B ...
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述