VBA Classes/Objects

后端 未结 2 1475
春和景丽
春和景丽 2020-12-16 06:47

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

2条回答
  •  一个人的身影
    2020-12-16 07:35

    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.

提交回复
热议问题