如果你真的不想看到 Mathieu 的 This,你可以把它包装成一个函数。这有点复杂,可以使用
- 将数据存储在公共变量中的第二个类。这将比 Mattieu 的实现稍慢
- 使用键访问数据的集合对象。这不需要在项目 exporer 的“类模块”列表中增加额外的混乱,但如果您快速连续地重复调用 This 会慢一点
下面给出了每个示例。如果你打破了类的初始化函数,你可以将me添加到监视窗口,并且只会列出Name属性
使用 2 个对象示例
插入一个类模块并将其命名为:InvisibleObjData
Option Explicit
Public Name As String
Public plop
Private Sub Class_Initialize()
Name = "new"
plop = 0
End Sub
插入一个类模块并将其命名为:InvisibleObj
Option Explicit
Private Function This() As InvisibleObjData
Static p As New InvisibleObjData 'static ensures the data object persists at successive calls
Set This = p
End Function
Private Sub Class_Initialize()
This.Name = "invisible man": Debug.Print Name
Me.Name = "test": Debug.Print Name
This.plop = 111: Debug.Print This.plop
End Sub
Property Let Name(aname As String): This.Name = aname: End Property
Property Get Name() As String: Name = This.Name: End Property
'_______________________________________________________________________________________
' in the immediate window type
'
' set x=new invisibleObj
如果您不喜欢将类拆分为两个对象,可以使用“包装”的集合对象生成类似的行为:
插入一个类模块并将其命名为:InvisibleCol
Option Explicit
Private Function This() As Collection
Static p As New Collection
'static ensures the collection object persists at successive calls
'different instances will have different collections
'note a better dictionary object may help
Set This = p
End Function
Private Function add2this(s, v)
'a better dictionary object instead of the collection would help...
On Error Resume Next
This.Remove s
This.Add v, s
End Function
Private Sub Class_Initialize()
add2this "name", "invisible man": Debug.Print Name
Me.Name = "test": Debug.Print Name
add2this "plop", 111
Debug.Print This("plop") ' use the key to access your data
Debug.Print This!plop * 2 ' use of the BANG operator to reduce the number of dbl quotes
' Note: This!plop is the same as This("plop")
End Sub
Property Let Name(aname As String): add2this "name", aname: End Property
Property Get Name() As String: Name = This!Name: End Property
'_______________________________________________________________________________________
' in the immediate window type
'
' set x=new invisibleCol