直接使用私有属性与使用 Get 和 Let/Set

Ric*_*ica 5 oop vba properties private class

初级 VBA 程序员(以及一般编程的初学者)希望了解有关如何有效进行 OOP 的更多信息。

有人可以解释或提供参考讨论使用 - 类模块内部 -Private Property Get和/或VBA 中的Let/Set语句与直接访问属性的好处/目的,尽管不需要对数据进行操作?

例子:

我创建了一个cDimension类(在 Excel 中)。这个类绘制线条作为Shape对象,以及一些其他不相关的东西。该DrawingScale变量允许根据需要缩放整个绘图。某些属性在获取/设置时需要进行操作,而其他属性则不需要。

因此,例如,pWidth需要进行缩放:

'clsDimension
Private pWidth As Single    
Private Property Get Width() As Single
    Width = pWidth
End Property
Private Property Let Width(w As Single)
    pWidth = w / DrawingScale
End Property
Run Code Online (Sandbox Code Playgroud)

pColor不需要任何输入或输出操作:

Private pColor As Integer
Private Property Get Color() As Integer
    Color = pColor
End Property
Private Property Let Color(c As Integer)
    pColor = c
End Property
Run Code Online (Sandbox Code Playgroud)

pWidth 属性是一个实例,在该实例中,对类本身内部的过程使用 Private Property Get 和 Let 方法对我来说很有意义。然而,我的问题是:是否有任何理由也使用私有属性方法来获取和设置/设置 pColor 属性,正如我上面给出的那样?

Public Function Line(sht As Worksheet, L As tLine, Optional c = vbBlack) As Shape
    Width = DistanceBetweenTwoPoints(L.first.x, L.first.y, _
                                     L.second.x, L.second.y) '<-- pWidth is scaled
    Color = c '<-- Vs. just using pColor = c
    Set Line = sht.Shapes.AddLine(L.first.x, L.first.y, L.second.x, L.second.y)
End Function
Run Code Online (Sandbox Code Playgroud)

提前致谢。

mwo*_*e02 3

如果您不操作传入或传出的值,则只需使用公共变量。与 Java 或 C++ 相比,VBA 更像 Python,因为从公共变量切换到“getter/setter”函数不会带来真正的损失

假设您从以下代码开始:

'clsCar
Public Speed As Double
Public Sub Drive()
    MsgBox "Driving at " & Speed & " MPH"
End Sub    


'Module1
Sub DriveCar()
    Set Car = New clsCar
    Car.Speed = 100
    Car.Drive  'shows msg:  "Driving at 100 MPH"
End Sub
Run Code Online (Sandbox Code Playgroud)

然后你认为开那么快是危险的,所以你想为你的车辆添加一个“调速器”并且需要更新你的类:

'clsCar
Private mSpeed As Double
Private Const SpeedLimit As Double = 55

Public Property Get Speed()
    Speed = mSpeed
End Property
Public Property Let Speed(Val As Double)
    If Val > SpeedLimit Then
        mSpeed = SpeedLimit
    ElseIf Val < 0 Then
        mSpeed = 0
    Else
        mSpeed = Val
    End If
End Property
Public Sub Drive()
    MsgBox "Driving at " & Speed & " MPH"
End Sub    


'Module1
'Note that no changes to this code are necessary; the change
'   is entirely encapsulated within the class (as it should be)
Sub DriveCar()
    Set Car = New clsCar
    Car.Speed = 100
    Car.Drive  'shows msg:  "Driving at 55 MPH"
End Sub
Run Code Online (Sandbox Code Playgroud)

Tim Williams 的评论是您经常听到的,作为在 VBA 中不必要地使用 Get/Let/Set 的理由,但这是其他语言(尤其是 C++ 和 Java)的好建议被误用于 VBA/VB6 的副产品。