变量类型的自定义类的父对象

时间:2018-11-01 11:37:55

标签: excel vba

我认为我正在VBA中编写相当复杂的内容,尽管我做了很多研究,但到目前为止我仍无法提出解决方案。不幸的是,我不是专家:)

我有两个班级,例如clsBuildingclsFactory都具有clsHeatDemand的实例。现在,我基于this的想法,尝试实现一种parent属性,以访问计算所需的基类中的某些值。

Friend Property Get Parent() As clsBuilding
    Set Parent = ObjFromPtr(parentPtr)
End Property
Friend Property Set Parent(obj As clsBuilding)
    parentPtr = ObjPtr(obj)
End Property

我现在的问题是parent可以是两种不同的类型,即使它们具有我需要的相同参数也是如此。因此,我想问的是,是否有一种方法可以像obj As Object那样简单地移交实例并仍然访问其属性?

我也使用Interfaces进行了尝试,但是如果有另一个更简单的解决方案,我会很高兴。

1 个答案:

答案 0 :(得分:0)

我不知道这是否可以帮助您,看看吧。

'具有不同父级的类

Option Explicit

Private m_parent As Variant

Public Property Get Parent() As Variant
    Set Parent = m_parent
End Property

Public Property Set Parent(ByVal vNewValue As Variant)
    Set m_parent = vNewValue
End Property

Public Function Name()
    If TypeName(m_parent) = "ParentA" Then
        Name = m_parent.Name
    Else
        Err.Raise 123, "Parent doesn't have Name"
    End If
End Function

Public Function Height()
    If TypeName(m_parent) = "ParentB" Then
        Height = m_parent.Height
    Else
        Err.Raise 456, "Parent doesn't have Height"
    End If
End Function

'ParentA

Public Name As String

Public Age As Integer

'ParentB

Public Height As Double

Public Weight As Double

'测试

Sub test()
    Dim c As Class
    Set c = New Class

    Dim pa As ParentA
    Set pa = New ParentA
    pa.Age = 5
    pa.Name = "Parent A"

    Dim pb As ParentB
    Set pb = New ParentB
    pb.Height = 15.5
    pb.Weight = 50.5

    Set c.Parent = pa
    Debug.Print c.Name


    Set c.Parent = pb
    Debug.Print c.Height
    Debug.Print c.Name
End Sub