Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

vba - How to prevent showing backing private fields of class properties in the Locals window?

Although 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. A 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

Why are both Name and pName shown in the Locals Window? Can I in some way get rid of pName?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As comments & answers already said, that's just the VBE being helpful.

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:

clean locals toolwindow

So what's going on here? What's this?

Here's 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

The class only has 1 private field, a user-defined type value named this, which holds all the encapsulated data members.

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:

locals toolwindow, 'this' field expanded

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...