VBA将父类传递给子类

时间:2016-07-05 19:16:04

标签: vba class subclass

我在SO上发现了一篇很棒的帖子,似乎正是我想要的:Is it possible to access a parent property from a child that is in a collection?但是我对它的改编给了我Object doesn't support this property or method.

我的代码现在可以使用Mat's Mug和Tomalak:

父类 - clsComputer

Option Explicit
Private pCD As clsCD

''''''''''''''''''''''''''''''
' CD property
''''''''''''''''''''''''''''''
Public Property Get CD() As clsCD
    If pCD Is Nothing Then
        Set pCD = New clsCD
        'Per Mat's Mug post, drop the parenthesis
        pCD.Initialze Me
    End If
    Set CD = pCD
End Property
Public Property Set CD(value As clsCD)
    pCD = value
End Property

儿童类 - clsCD

Option Explicit

Private pParent As clsComputer

'''''''''''''''''''''''''''''
' Status property - READ ONLY
'''''''''''''''''''''''''''''
Public Property Get Status(Optional strHost As String) As String
    Dim strResult As String

    If strHost = "" Then strHost = Me.Parent.HostName

    strResult = RunCMD("cmd /c ""winrs -r:" & strHost & _
        " reg query hklm\system\currentcontrolset\services\cdrom /v start""")
    If InStr(1, strResult, "0x4", vbTextCompare) Then
        Status = "Disabled"
    Else
        Status = "Enabled"
    End If
End Property

'''''''''''''''''''''''''
' Parent property
'''''''''''''''''''''''''
Public Property Get Parent() As clsComputer
    Set Parent = pParent
End Property

'Because as Tomalak points out, you use Set with Objects.
Public Property Set Parent(Obj As clsComputer)
    Set pParent = Obj
End Property

'''''''''''''''''''''''''
' Initialize Method
'''''''''''''''''''''''''
Public Sub Initialize(Obj As clsComputer)
    Set Me.Parent = Obj
End Sub

代码模块 - Module1

Sub test()
    Dim oPC As clsComputer
    Set oPC = New clsComputer
    Debug.Print "CD Status: " & oPC.CD.Status
End Sub

如果我测试我,它是一个对象(例如,If IsObject(Me) Then Stop评估为真),当我键入Me.时,智能感知显示clsComputer中的所有属性和方法。本地窗口将我显示为clsComputer宾语。我知道要检查的一切都说我是一个clsComputer对象,所以我做错了什么?

3 个答案:

答案 0 :(得分:2)

$('div.delayed').each(function()
{   
    var timeoutDelay = $(this).data('timeout'),
        el = $(this);

    setTimeout(function()
    {
        el.hide();
    }, timeoutDelay);
});

答案 1 :(得分:2)

经典。

pCD.Initialize (Me) 'Error occurs on this line when using F8

删除括号。

pCD.Initialize Me

完成。

围绕参数的括号强制它评估并传递ByVal (无论程序的签名是什么) - 并且因为您可能还没有定义默认属性对于clsComputer,评估会爆炸,运行时甚至不会进入Initialize方法。

也就是说,按值传递对象引用没有错。事实上,这就是C#和VB.NET默认做的事情 - 考虑传递任何参数ByVal

答案 2 :(得分:0)

我不是在我的电脑上,所以只是盲目编码

尝试使用 clsComputer

Option Explicit
Private pCD As clsCD

''''''''''''''''''''''''''''''
' CD property
'''''''''''''''''''''''''''''' 
Public Property Get CD() As clsCD
    Set CD = pCD
End Property

Public Property Set CD(value As clsCD)
    pCD = value
End Property

Sub Class_Initialize()
    Set pCD = New clsCD
    pCD.Initialize(Me)
End Property