对于我来说,这是一个关于学习面向对象方法的问题,因为它与VBA语法有关。假设我创建了几个类,如Car,Truck,Bus等。我创建了另一个类SpeedCalculator,我的车辆实例将实例化并包含。 (作为一个新手,让我注意到这是一个很好的时间来宣布一个类是静态的而不是实例化它 - 哪个vba不能做我不认为......。)现在这个速度计算器将是没有简单的车速表。相反,它将根据温度,风速,RPM等计算速度 - 请与此一起,仅为了示例。
现在问题是所包含的对象如何收集其输入,这些输入仅在容器对象中可用(车辆对象可能实现接口(如果VBA甚至可以这样做......))。 “家长”。是错的,我最终想通了,b / c parent-child是一个继承关系(VBA没有,再次),不是包含关系,包含对象的父是Excel应用程序(不是我的对象) 。因此,如果有另一个关键字来引用容器属性,那似乎会很好。我希望我不会错过一些简单的事情。或者更多的情况是,这种引用会破坏面向对象的封装原则?
我想第二种方法是将容器传递给包含的,通过“Me”作为参数。但是你必须将所有包含的方法相乘,要么重载它们(如果VBA甚至可以这样做......),要么使用不同命名的版本 - 由于容器的类型不同(我们可以更理想化和避免声明为变体或“对象”?)。
然后门#3将是最后一扇门,我猜?这将是一个(恼人的)一连串的争论。所有这些的定义往往会破坏我整洁的小计算器类的目的?
答案 0 :(得分:6)
答案 1 :(得分:4)
我不确定这是否是您要找的,但我会试一试。如果Car类包含一个Speedometer类,Car包含Windspeed和Acceleration属性,Speedometer包含Mass属性,速度定义为Windspeed times Acceleration除以Mass,那么这就是我如何设置它。
在课堂上
Private mlCarID As Long
Private mdWindSpeed As Double
Private mdAcceleration As Double
Private mclsSpeedometer As CSpeedometer
'Getters and setters
Public Property Get CarID() As Long: CarID = mlCarID: End Property
Public Property Let CarID(ByVal lCarID As Long): mlCarID = lCarID: End Property
Public Property Get Acceleration() As Double: Acceleration = mdAcceleration: End Property
Public Property Let Acceleration(ByVal dAcceleration As Double): mdAcceleration = dAcceleration: End Property
Public Property Get WindSpeed() As Double: WindSpeed = mdWindSpeed: End Property
Public Property Let WindSpeed(ByVal dWindSpeed As Double): mdWindSpeed = dWindSpeed: End Property
'read only property to the speedometer class
Public Property Get Speedometer() As CSpeedometer
Set Speedometer = mclsSpeedometer
End Property
'create the child and set the parent property
Private Sub Class_Initialize()
Set mclsSpeedometer = New CSpeedometer
Set mclsSpeedometer.Parent = Me
End Sub
Private Sub Class_Terminate()
Set mclsSpeedometer.Parent = Nothing
Set mclsSpeedometer = Nothing
End Sub
'pass through property
Public Property Get Speed() As Double
Speed = Me.Speedometer.Speed
End Property
课堂CSpeedometer
Private mdMass As Double
Private mclsParent As CCar
Public Property Get Mass() As Double: Mass = mdMass: End Property
Public Property Let Mass(ByVal dMass As Double): mdMass = dMass: End Property
Public Property Get Parent() As CCar
Set Parent = mclsParent
End Property
Public Property Set Parent(clsCar As CCar)
Set mclsParent = clsCar
End Property
Public Property Get Speed() As Double
'references to parent properties
Speed = Me.Parent.WindSpeed * Me.Parent.Acceleration / Me.Mass
End Property
在标准模块中
Sub GetSpeed()
Dim clsCar As CCar
Set clsCar = New CCar
clsCar.CarID = 1
clsCar.WindSpeed = 10
clsCar.Acceleration = 5
clsCar.Speedometer.Mass = 100
Debug.Print clsCar.Speed
End Sub
您必须确保正确销毁父/子关系,否则会导致内存泄漏。我使用CopyMemory设置父属性以避免该特定问题。这里描述了http://www.dailydoseofexcel.com/archives/2007/12/28/terminating-dependent-classes/#comment-29661