1

我有一个类模块 MyVBAclass,它有一个自定义 COM 类的成员

Private mMyCOMclass As MyCOMclass
Public Property Get InnerClass() As MyCOMclass
    Set InnerClass = mMyCOMclass
End Property
Public Property Let InnerClass(value As MyCOMclass)
    Set mMyCOMclass = value
End Property
Private Sub Class_Initialize()
    Set mMyCOMclass = New MyCOMclass
End Sub

MyCOMclass 实现了 Clone() 和 CopyTo() 方法,Clone 返回 MyCOMclass 的新实例,CopyTo 只是将属性复制到已经初始化的对象。这是我遇到的问题,如果有人能解释如何避免它,那就太好了。

Dim MyVBAinstance As MyVBAclass
Set MyVBAinstance = New MyVBAclass

Dim COMinstance As MyCOMclass, copyOfCOM As MyCOMclass
Set COMinstance = New MyCOMclass
Set copyOfCOM = New MyCOMclass

' Do some stuff with COMinstance

Call COMinstance.CopyTo(copyOfCOM) ' Works fine
MyVBAinstance.InnerClass = COMinstance.Clone() ' Works fine even without Set

Call COMinstance.CopyTo(MyVBAinstance.InnerClass) ' DOESN'T WORK
4

1 回答 1

2

面向对象的思想是对象将其成员隐藏在外部世界之外。和GET属性SET充当“网关”。这样,没有例程可以简单地覆盖更改下面的对象MyVBAinstance.InnerClass。你需要做的是:

Dim objTemp as As MyCOMclass
Set objTemp = New MyCOMclass 'this will reserve the memory and store the pointer in objTemp
Call COMinstance.CopyTo(objTemp) 'this will fill the allocated memory
Set MyVBAinstance.InnerClass = objTemp 'this will copy the pointer from objTemp to MyVBAinstance.InnerClass

如果你想公开你的类的一些私有成员,你需要像你一样提供PROPERTY GETand PROPERTY SET/方法。每次访问属性时都会调用 -当您将对象/值分配给属性时会调用 / 。PROPERTY LETGETPROPERTY SETPROPERTY LET

如果属性是对象,则需要使用PROPERTY SET- 如果它是本机类型(整数、字符串等),则必须使用PROPERTY LET.

以同样的方式,您需要使用SET(例如Set MyVBAInstance.InnerClass = anotherObject)将对象分配给属性,但不使用本机类型SET(例如' MyVBAInstance.Name = "Test"`)

因此,在您的代码中替换LETSET

Public Property Set InnerClass(value As MyCOMclass)
    Set mMyCOMclass = value
End Property

然后还在SET代码中使用关键字:

Set MyVBAinstance.InnerClass = COMinstance.Clone()

于 2013-02-18T10:07:05.380 回答