使用类接口还是使用 Variant 变量引用类模块?

问题描述

我想知道下面提到的哪种方法在引用类模块时是最好的(以及在什么情况下)?

让我具体说明我的意思。
(我在下面使用的代码来自https://excelmacromastery.com/

以下是使用类接口的示例:

Sub Main()

    ' Get the range of data
    Dim rg As Range
    Set rg = shData.Range("A1").CurrentRegion
    
    ' Declare the interface variable - this can reference any class
    ' that implements iInterest.
    Dim oInterest As iInterest
    
    ' data variables
    Dim amount As Double,interestType As String
    
    ' Read through the data
    Dim i As Long,result As Double
    For i = 2 To rg.Rows.Count
    
        ' read the current row to variables
        amount = rg.Cells(i,1).Value
        interestType = rg.Cells(i,2).Value

        ' Get the interest object
        Set oInterest = ClassFactory(interestType)
        
        ' Calculate the interest
        oInterest.Calculate amount
        
        ' some code
        
        ' Print the interest to the Immediate Window
        oInterest.PrintResult
          
    Next i

End Sub
Function ClassFactory(ByVal interestType As String) As iInterest

    Dim oInterest As iInterest
            
    If interestType = "A" Then
        Set oInterest = New clsInterestA
    ElseIf interestType = "B" Then
        Set oInterest = New clsInterestB
    ElseIf interestType = "C" Then
        Set oInterest = New clsInterestC
    Else
        MsgBox "Invalid type " & interestType
    End If
    
    Set ClassFactory = oInterest

End Function
' The class for calculating Interest type A
Implements iInterest

Private m_Amount As Double

' Calculate the interest
Sub iInterest_Calculate(ByVal amount As Double)
    m_Amount = amount * 1.1
End Sub

' Print the result to the Immediate Window
Sub iInterest_PrintResult()
    Debug.Print TypeName(Me) & ": " & m_Amount
End Sub
' The Interface Class named "iInterest" - this is implemented by clsInterestA,clsInterestB and clsInterestC
Sub Calculate(ByVal amount As Double)
End Sub

Sub PrintResult()
End Sub

所以我们有一个标准模块,一个创建适当的类对象(“类工厂”)的函数,几个类模块(只包括一个用于说明目的)和类模块接口。

所以标准模块的名为“Main”的子函数和名为“ClassFactory”的函数声明了接口变量:

Dim oInterest As iInterest

这可以引用任何实现名为“iInterest”的类模块接口的类。

这是不使用类接口的另一种方法

sub Main()
'Rest of the Code same as before

Dim oInterest As Variant 'PrevIoUsly: Dim oInterest As iInterest

end sub
Function ClassFactory(ByVal interestType As String) As Variant
'Rest of the Code same as before

Dim oInterest As Variant 'PrevIoUsly: Dim oInterest As iInterest

end sub

这里使用了名为“Main”的相同标准模块的 Sub 和名为“ClassFactory”的函数,但声明了一个 Variant 变量来引用相同的类模块(不再实现任何类模块接口)。

所以我的问题如下:
  • 使用类模块接口与使用 Variant 变量来引用任何类的第二种技术相比有什么优缺点?

  • 我应该什么时候使用“接口”方法与使用 Variant 变量引用类的方法

这两种方法我都试过了,但我还是不清楚。

也许这可能是优点(但我不是 VBA 专家,所以我只是猜测):

  • 与将任何类声明为 Variant 相比,将引用任何类的变量声明为“接口类”时分配的内存量更少或完全相同。
  • 实现类模块接口的类模块可以通过窗口顶部的代码窗口下拉列表轻松访问“类接口过程名称”。

非常感谢任何支持/见解。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)