我正在尝试创建一个类模块,该模块接受用户输入的两个参数,然后进行计算以创建返回计算值的私有(private)属性
这是我到目前为止得到的:
'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
我评论的部分这味道
是我拼凑而成的,所以下面的代码给出了预期的行为:
'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
我认为这是错误的,因为
- 我正在使用 get 属性来调用函数,但我无法找到一种方法将此调用放置在代码的其他位置。
- 如果我不在模块中的某个位置调用
clsItem.Total
,mTotal
将永远不会更新。
我尝试使用Class_Initialize()
,但由于.Quantity
和.Price
,它给出了0
尚未传递给类(class)。
那么我怎样才能做到这一点呢?
最佳答案
- 删除
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
关于excel - 如何改进这个类模块定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53725989/