VBA:为什么使用属性而不是子例程或函数? [英] VBA: Why Use Properties Instead of Subroutines or Functions?

查看:84
本文介绍了VBA:为什么使用属性而不是子例程或函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么当我们可以简单地使用子例程或函数传递和返回参数时,为什么需要在VBA类中使用属​​性LetGetSet?

Why do we need to use property Let, Get and Set in a VBA class when we can simply pass and return our arguments using subroutines or functions?

推荐答案

我认为简单的答案是属性是类的特征,而方法(子例程)是动作.

I think that the short answer is that properties are characteristics of the class while methods (subroutines) are actions.

我对此的解释是,属性是形容词",方法是动词".我们可以做个比喻来说明这一点:我们有两个NHL守门员(让我们将其创建为clsGoalie的成员),Carey Price和Dustin Tokarski.每个对象都有特定于其唯一目标"对象的属性,我们称其为保存百分比(pSavePercentage).两个守门员都需要使用完全相同的方法来停止射门(比如说Private Sub BlockShot),但是它们的独特属性会影响该动作的性能.

My interpretation of this is that properties are the "adjectives" and methods are the "verbs". We could make an analogy to help illustrate this: We have two NHL goalies (let's create them as members of clsGoalie), Carey Price and Dustin Tokarski. Each has a property specific to their unique "goalie" object which we call save percentage (pSavePercentage). Both goalies require the exact same method for stopping a shot on net (Let's say Private Sub BlockShot) but their unique properties will influence the performance of that action.

为什么要使用属性而不是返回值来定义类的特征的答案是,属性扩展了对象,或者实质上是定义了对象.返回值不能用于引用它们返回的对象.回到守门员类比...让我们假设我们用子程序定义了每个守门员的扑救百分比.我们可以使其工作,但是在我们的main方法中将需要更多代码.首先,我们必须将将SavePercentage设置为Double值"(已经可以看到我们已经超出了对象范围).接下来,"SavePercentage = Price.calcSavePercentage".最后,我们将不得不编写一个全新的方法(在Main或其他模块中),然后将double类型的新变量传递给...这一点我们甚至都不知道谁在网上.普莱斯保存了那张照片还是托卡尔斯基(Tokarski)?令人困惑.在这种情况下,如果将保存百分比设为"clsGoalie"类的属性,我们将更好地利用OOP的功能:干净的代码和封装.

The answer to why we would define the characteristics of a class with properties instead of return values is that properties extend the object, or in essence, define the object. Return values can not be used to reference back to the object they originated from. Back to our goalie analogy... Let's suppose we defined the save percentage of each of our goalies with a subroutine. We could make it work but it would require more code in our main method. First we would have to 'Dim SavePercentage As Double' (already you can see that we've stepped outside of our object). Next, 'SavePercentage = Price.calcSavePercentage'. Finally, we would have to write a whole new method (in our Main or some other module) that we would then pass our new variable of type double to... A this point we don't even know who's in net. Did Price save that shot or was it Tokarski? Confusing. In this instance, had we made save percentage a property of the class "clsGoalie" we would better leverage the power of OOP: clean code and encapsulation.

希望这会有所帮助.

这篇关于VBA:为什么使用属性而不是子例程或函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆