从Get属性引用Set属性

时间:2011-05-29 17:58:47

标签: vba class-design

我在另一个SO问题中发现了这个vba代码。在类的Get属性中引用Set属性有什么意义吗?

Private WithEvents mctlEventButton As MSForms.CommandButton

Public Property Set EventButton(ctlButton As MSForms.CommandButton)
Set mctlEventButton = ctlButton
End Property

为什么这样? ...

Public Property Get EventButton() As MSForms.CommandButton
Set EventButton = mctlEventButton
End Property

代码显示了如何使用collections迭代一组控件。问题实际上并不是关于代码的那一部分,所以它在问题中没有得到解决。使用问题中的示例,我遇到了我在此处发布的位的问题,因为Get属性正在使用Set属性。那么什么时候有用呢?

以下是SO问题的链接:object array or collection in VBA Excel

1 个答案:

答案 0 :(得分:1)

Public Property Get EventButton() As MSForms.CommandButton
   Set EventButton = mctlEventButton
End Property

在上面的代码中,Set EventButton = mctlEventButton 不会调用以下内容(尝试逐步执行代码&您将看到它不会进入Set

Public Property Set EventButton(ctlButton As MSForms.CommandButton)
   Set mctlEventButton = ctlButton
End Property

另一方面,它作为用于返回值的语句 实际上,将Get视为

Public function EventButton() As MSForms.CommandButton
   Set EventButton = mctlEventButton  'returning the value from the function
End Property

以一个属性的形式包装,供开发人员进行获取/设置。