VBA 嵌套类

问题描述 投票:0回答:1

我有一个可以编译的 VBA 嵌套类,但我想更好地格式化它以供扩展使用。

当前要进入动物/猫类,需要使用Animal.clsCat。我的问题是,有没有办法使用 Animal.Cat 来代替,同时仍然单独保留一个名为 Cat 的类?由于 VBA 限制不区分大写“Cat”和小写“cat”,我正在使用一种匈牙利表示法。

如有任何帮助,我们将不胜感激。

当前: Animal.clsCat.name

理想: 动物.猫.名称

Class clsCat

Option Explicit

Dim propertyName As String

Public Property Get name() As String
    name = propertyName
End Property

Public Property Let name(ByVal propertyNameValue As String)
    propertyName = propertyNameValue
End Property

Sub NameSub(name As String)
    Debug.Print "Cats name is: " & name
End Sub

Function Speak() As String
    Speak = "says Meow!"
End Function

Class clsDog

Option Explicit

Dim propertyName As String

Public Property Get name() As String
    name = propertyName
End Property

Public Property Let name(ByVal propertyNameValue As String)
    propertyName = propertyNameValue
End Property

Sub NameSub(name As String)
    Debug.Print "Dogs name is: " & name
End Sub

Function Speak() As String
    Speak = "says Roof!"
End Function

Class clsAnimal

Option Explicit

Dim Cat As New clsCat
Dim Dog As New clsDog
Dim Fish As New clsFish

'Cat
Public Property Get Cat() As clsCat
    Set clsCat = Cat
End Property

Public Property Set clsCat(ByVal newValue As clsCat)
    Set Cat = newValue
End Property


'Dog
Public Property Get clsDog() As clsDog
    Set clsDog = Dog
End Property

Public Property Set clsDog(ByVal newValue As clsDog)
    Set Dog = newValue
End Property

Module mTest

Sub AnimalTest()

    Dim Animal As New clsAnimal
    'Dim Cat As New clsCat
    Dim Dog As New clsDog
    
    Animal.clsCat.name = "Cat"
    Animal.clsDog.name = "Dog"
    Cat.name = "TrueCat"
    
    ' SUB TEST
    Animal.clsCat.NameSub ("CatCat")
    Animal.clsDog.NameSub ("Doggo")
    
    ' DEBUG
    Debug.Print "---"
    Debug.Print Animal.clsCat.name
    Debug.Print Animal.clsDog.name
End sub
vba class nested polymorphism
1个回答
0
投票

我的设置方法如下。我简化了代码来说明概念:

猫类

Option Explicit

Private m_Name As String

Public Property Get Name() As String
    Name = m_Name
End Property

Public Property Let Name(ByVal Value As String)
    m_Name = Value
End Property

Public Sub NameSub(Name As String)
    Debug.Print "Cats name is: " & Name
End Sub

Public Function Speak() As String
    Speak = "says Meow!"
End Function

动物类

Option Explicit

Private m_Cat As Cat

Private Sub Class_Initialize()
   Set m_Cat = New Cat
End Sub

Public Property Get Cat() As Cat
    Set Cat = m_Cat
End Property

Public Property Set Cat(ByVal Value As Cat)
    Set m_Cat = Value
End Property

测试

Dim Animal As Animal
Set Animal = new Animal

Animal.Cat.Name = "Cat"
Debug.Print Animal.Cat.Name
Debug.Print Animal.Cat.Speak
Animal.Cat.NameSub "CatCat"
© www.soinside.com 2019 - 2024. All rights reserved.