我正在尝试创建一个使用两个由用户输入的参数的类模块,然后进行计算以创建一个私有属性,该私有属性返回一个计算出的值
这是我到目前为止所得到的:
'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
我认为这是错误的,因为
clsItem.Total
模块中的某个地方,mTotal
将永远不会更新。我尝试使用Class_Initialize()
,但由于0
和.Quantity
还没有传递给类,因此它给出了.Price
。
那我该怎么做呢?
答案 0 :(得分:2)
SetTotal
Get Total()
所以你最终会得到
'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