VBA difference between public variable and property

后端 未结 2 1105
执笔经年
执笔经年 2021-01-02 07:32

What is the difference between

Public Variable As Integer

and

Private pVariable As Integer

Public Property Let Variable(By         


        
2条回答
  •  清酒与你
    2021-01-02 08:09

    A property allows external access as though the property was a public field, while allowing the class to keep control of the data.

    The Get property may compute a "variable" that doesn't actually exist in the class. E.g. a mass Get property might return the product of density times volume.

    Private density as Double
    Private volume as Double
    Private potentialEnergy
    
    Public Property Get mass() As Double
       mass = density*volume
    End Property 'Property Get mass
    

    A Let property might check validity, e.g. not accept a negative volume. Or it can keep an object's field properties in sync:

    Public Property Let density(rho as Double)
       if rho > 0 then
          density = rho
          potentialEnergy = density * volume * gravity * height
    End Property 'Property Get mass
    

    You can also make a property read-only (or write-only -- not used much) by omitting the Let or Get property.

    Other than a very slight degradation in performance, it's good practice to use properties from the start for any fields that you allow public access, even if the properties are initially trivial, to facilitate future modifications to the class.

提交回复
热议问题