VBA类/对象 [英] VBA Classes/Objects
问题描述
尽管有经验的VBA程序员,但这是我第一次创建自己的类(对象)。令我感到惊讶的是,本地窗口中的所有属性都是重复的。小例子(在 End Sub处中断):
Allthough an experienced VBA programmer it is the first time that I make my own classes (objects). I am surprised to see that all properties are 'duplicated' in the Locals Window. Small example (break at 'End Sub'):
' Class module:
Private pName As String
Public Property Let Name(inValue As String)
pName = inValue
End Property
Public Property Get Name() As String
Name = pName
End Property
' Normal module:
Sub Test()
Dim objTest As cTest
Set objTest = New cTest
objTest.Name = "John Doe"
End Sub
为什么在Locals窗口中同时显示Name和pName?我可以以某种方式摆脱pName吗?
Why is both Name and pName shown in the Locals Window? Can I in some way get rid of pName?
最好的问候,
Helge
Best regards, Helge
推荐答案
作为注释&
但是,如果您发现在 locals 中列出私有字段和公共成员很麻烦, >工具窗口,有一种方法可以很好地清理它-在这里,我将 Test
过程放入 ThisWorkbook
内,名为 Class1
的类:
However if you find it noisy to have the private fields and public members listed in the locals toolwindow, there's a way to nicely clean it up - here I put the Test
procedure inside ThisWorkbook
, and left the class named Class1
:
那么这是怎么回事?什么是 c?
So what's going on here? What's this
?
这里是 Class1
:
Option Explicit
Private Type TClass1
Name As String
'...other members...
End Type
Private this As TClass1
Public Property Get Name() As String
Name = this.Name
End Property
Public Property Let Name(ByVal value As String)
this.Name = value
End Property
该类只有1个私有字段,一个名为 this
的用户定义类型值,其中包含所有封装的数据成员。
The class only has 1 private field, a user-defined type value named this
, which holds all the encapsulated data members.
因此,属性的基础字段被有效隐藏,或者将它们全部重新组合在 this $下c $ c>,因此除非想查看它们,否则您将看不到基础字段值:
As a result, the properties' underlying fields are effectively hidden, or rather, they're all regrouped under this
, so you won't see the underlying field values unless you want to see them:
此外,您还可以不再需要任何伪匈牙利前缀,这些属性的实现非常清晰,并且所有属性中最好的标识符名称与其后备字段完全相同。
And as an additional benefit, you don't need any pseudo-Hungarian prefixes anymore, the properties' implementations are crystal-clear, and best of all the properties have the exact same identifier name as their backing field.
这篇关于VBA类/对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!