VBA:为什么使用属性而不是子例程或函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5497575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 12:55:46  来源:igfitidea点击:

VBA: Why Use Properties Instead of Subroutines or Functions?

classvbapropertiesarguments

提问by Nigel Davison

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

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

回答by MikeD

You don't need to ... for 90% of all applications standard VBA is just right. Using classes you have more "logical control" over your code.

您不需要...对于 90% 的所有应用程序标准 VBA 都恰到好处。使用类,您可以对代码有更多的“逻辑控制”。

Suppose you have a function Function IsUnique(MyArg as String) as Booleanthat looks up a table of persons with a name passed in MyArgand returns TRUEif the name is not found in the table. Nothing prevents you for instance to call this function and pass the string of the favourite vegetable the user chose. You will still get a syntactically correct program, despite the fact that this call will always return TRUEbecause vegetables are stored somewhere else in this application.

假设您有一个函数Function IsUnique(MyArg as String) as Boolean,该函数通过传入的姓名查找人员表,如果在表中找不到该姓名则MyArg返回TRUE。例如,没有什么可以阻止您调用此函数并传递用户选择的最喜欢的蔬菜的字符串。你仍然会得到一个语法正确的程序,尽管这个调用总是会返回,TRUE因为蔬菜存储在这个应用程序的其他地方。

Now suppose you have a class PersonClasscontaining functions (=property) Nameand IsUnique()

现在假设您有一个PersonClass包含函数 (=property)NameIsUnique()

Your code finally you would maybe like this

你的代码最终你可能会喜欢这个

Dim MySpouse as PersonClass
    Set MySpouse = New PersonClass
    MySpouse.Name = "Fanny Hill"
    If MySpouse.IsUnique() Then
        MySpouse.Insert
    End If

What seems like an overkill really encapsulatesthe code blocks, functions and variables pertaining to a Person (here called methodsand properties) into a class and make it more obvious to your code what you are doing with a variable that makes use of that class template (aka. an instanceof that class)

看似矫枉过正的做法实际上是属于 Person 的代码块、函数和变量(此处称为方法属性封装到一个类中,并使您的代码更加明显地了解您正在使用一个使用该类模板的变量做什么(又名。该类的一个实例

Typical example: IP address arithmetic ..... (add IP's, find base or broadcast addresses, convert between various mask notations, check two ranges for overlap, find net mask sourrounding two or more IP-@es etc. etc. etc.) needed in a dozen of applications: write the class module once, and once tested you can easily reuse it.

典型示例:IP 地址算法.....(添加 IP,查找基址或广播地址,在各种掩码符号之间转换,检查两个范围是否重叠,查找围绕两个或多个 IP-@es 等的网络掩码等等。 ) 需要在十几个应用程序中:编写一次类模块,经过测试后,您可以轻松地重用它。

Another advantage with classes is that when entering the code in the VBA editor, the code completion tells you exactly what you can do with a class (i.e. all properties and methods are presented in a dropdown list) - a comfort you don't have with procedures and functions (they only tell you the argument names and types)

类的另一个优点是,当在 VBA 编辑器中输入代码时,代码完成会准确地告诉您您可以用类做什么(即所有属性和方法都显示在下拉列表中)——这是您没有的舒适感过程和函数(它们只告诉你参数名称和类型)

Enough?

足够的?

回答by миша яцкевич

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

我认为简短的回答是属性是类的特征,而方法(子例程)是动作。

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.

我对此的解释是属性是“形容词”,方法是“动词”。我们可以做一个类比来帮助说明这一点:我们有两个 NHL 守门员(让我们将他们创建为 clsGoalie 的成员),Carey Price 和 Dustin Tokarski。每个人都有一个特定于他们独特的“守门员”对象的属性,我们称之为保存百分比 (pSavePercentage)。两个守门员都需要完全相同的方法来阻止网上射门(让我们说 Private Sub BlockShot),但他们独特的属性会影响该动作的表现。

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.

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

Hope this helps a bit.

希望这个对你有帮助。

回答by Patrick Honorez

Properties are for Classes. So I guess your real is question is more: "why use class modules ?". And indeed, you can build excellent apps for years without that need.
I started using those for very specific uses, like reading complex text files (mainframe printed reports with logical records spanning over several physical lines) or getting specific info from huge and complex Excel worksheets.
Once you get a class done that simulates the item you want to read, you can reuse that class from app to app, and concentrate on the logic of you specific app, not on the logic of that same old reading that same old file for example.

属性用于类。所以我想你真正的问题是更多:“为什么使用类模块?”。事实上,您可以在没有这种需要的情况下构建出色的应用程序多年。
我开始将它们用于非常特定的用途,例如阅读复杂的文本文件(大型机打印的报告,逻辑记录跨越多条物理线)或从庞大而复杂的 Excel 工作表中获取特定信息。
一旦你完成了一个模拟你想要阅读的项目的类,你可以在应用程序之间重用该类,并专注于特定应用程序的逻辑,而不是相同的旧文件的逻辑,例如阅读同一个旧文件.

回答by user13055167

Moreover, Let/Get combination or Set/Get combination sets a discipline for type of argument (for Let/Set) and return value (Get) so that functions can be used on left hand side of an assignment statement. Makes coding crisp!

此外,Let/Get 组合或 Set/Get 组合为参数类型(对于 Let/Set)和返回值(Get)设置了规则,以便可以在赋值语句的左侧使用函数。使编码清晰!