如何改进此类模块定义



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

到目前为止,我得到的是:

'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.TotalmTotal将永远不会更新

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

那么我该怎么做呢?

  1. 移除SetTotal
  2. 只需计算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

最新更新