如何改善这个Class Module定义

时间:2018-12-11 14:13:29

标签: excel vba oop

我正在尝试创建一个使用两个由用户输入的参数的类模块,然后进行计算以创建一个私有属性,该私有属性返回一个计算出的值

这是我到目前为止所得到的:

'clsItem Class Module
Option Explicit

Private mQt As Integer
Private mPrice As Double
Private mTotal As Double

Public Property Let Quantity(Value As Integer)
    mQt = Value
End Property

Public Property Let Price(Value As Double)
    mPrice = Value
End Property

Private Function SetTotal(mQt As Integer, mVl As Double)
    mTotal = mQt * mPrice
End Function

Public Property Get Quantity() As Integer
    Quantity = mQt
End Property

Public Property Get Price() As Double
    Price = mPrice    
End Property

Public Property Get Total() As Double
    SetTotal mQt, mPrice 'This smells
    Total = mTotal   
End Property

我评论过This smells的那部分是我所穿的,所以下面的代码给出了预期的行为:

'Object Module
Sub TestCls()
    Dim basicItem As clsItem

    Set basicItem = New clsItem
    With basicItem
        .Quantity = 100
        .Price = 12.5
    End With
    Debug.Print basicItem.Total
End Sub

我认为这是错误的,因为

  1. 我正在使用get属性来调用函数,但我想不出一种在代码上其他位置放置此调用的方法。
  2. 如果我不调用clsItem.Total模块中的某个地方,mTotal将永远不会更新。

我尝试使用Class_Initialize(),但由于0.Quantity还没有传递给类,因此它给出了.Price

那我该怎么做呢?

1 个答案:

答案 0 :(得分:2)

  1. 删除SetTotal
  2. 只需计算您的Get Total()
  3. 中的总数

所以你最终会得到

'clsItem Class Module
Option Explicit

Private mQt As Integer
Private mPrice As Double

Public Property Let Quantity(Value As Integer)
    mQt = Value
End Property

Public Property Get Quantity() As Integer
    Quantity = mQt
End Property


Public Property Let Price(Value As Double)
    mPrice = Value
End Property

Public Property Get Price() As Double
    Price = mPrice    
End Property


Public Property Get Total() As Double
    Total = mQt * mPrice
End Property