VBA是OOP语言吗,它支持多态吗? [英] Is VBA an OOP language, and does it support polymorphism?

查看:248
本文介绍了VBA是OOP语言吗,它支持多态吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上是在第一个 VBA 项目上工作. (来自 C ++ )

I am actually working on my first VBA project. (come from C++)

我想通过实现类和多态性来改进 Microsoft Excel 工作簿使用的现有 VBA 项目.

I would like to improve an existing VBA project used by a Microsoft Excel workbook by implementing classes and polymorphism.

我的问题是:

1-我阅读了很多文章/论坛,这些文章/论坛解释了 VBA 不是面向对象编程( OOP )语言,并且不支持多态.

1 - I read a lot of articles/forums which explain that VBA is not an Object Oriented Programming (OOP) language and do not support Polymorphism.

其中一些人建议使用关键字实现的变通办法.

Some of them propose a workaround using the keyword Implements.

2-我还发现了一些网页,例如这个解释了如何使用 Inherits Overrides Overridable MustOverrides .

2 - I also found some webpages like this one which explain how to perform OOP and polymorphism in VBA using keywords like Inherits, Overrides, Overridable, MustOverrides.

所以我的问题是:

VBA OOP 语言,并且它支持多态吗?

Is VBA an OOP language, and does it support polymorphism ?

推荐答案

OOP坐在4个支柱"上:

OOP is sitting on 4 "pillars":

  • 抽象-抽象逻辑和概念可以轻松完成通过在类模块中定义对象.严格来说,抽象也可以通过使用有意义的标识符并将过程代码提取到方法(类成员)中来实现.

  • Abstraction - Abstracting logic and concepts can easily be done by defining objects in class modules. Strictly speaking, abstraction is also achieved by using meaningful identifiers and extracting procedural code into methods (class members).

下面是用VBA编写的过程的示例,该过程演示了抽象:

Here's an example of a procedure written in VBA that demonstrates abstraction:

Public Sub Test(ByVal checkin As Date, ByVal checkout As Date, ByVal custType As CustomerType)
    Dim finder As New HotelFinder
    InitializeHotels finder
    Debug.Print finder.FindCheapestHotel(checkin, checkout, custType)
End Sub

一目了然,很容易看出这个Test过程的作用,因为抽象水平非常高:实现细节抽象进入更专业的对象和方法.

It's easy to tell what this Test procedure does at a glance, because the abstraction level is very high: the implementation details are abstracted away into more specialized objects and methods.

封装-类可以具有通过属性公开的私有字段;可以将类制作为PublicNotCreatable,将类型有效地暴露给其他VBA项目-并花费一些精力(通过导出类模块,在您喜欢的文本编辑器中将其打开,手动编辑类属性,然后重新导入该模块) ,您可以实现实际的只读类型.没有参数化构造函数的事实无关紧要-只需编写一个工厂方法,该方法将使用您喜欢的所有参数并返回一个实例.这是COM,COM仍然喜欢工厂.

Encapsulation - Classes can have private fields exposed by properties; classes can be made PublicNotCreatable, effectively exposing types to other VBA projects - and with a little bit of effort (by exporting the class module, opening it in your favorite text editor, manually editing class attributes, and re-importing the module), you can achieve actual read-only types. The fact that there are no parameterized constructors is irrelevant - just write a factory method that takes all the parameters you like and return an instance. This is COM, and COM likes factories anyway.

这是上面代码片段中的HotelFinder类如何封装 对象并且仅通过Property Get访问器公开它的示例-此类之外的代码根本无法Set此参考文件是封装的:

Here's an example of how the HotelFinder class from the above snippet encapsulates a Collection object and only exposes it through a Property Get accessor - code outside this class simply cannot Set this reference, it's encapsulated:

Private Type TFinder
    Hotels As Collection
End Type
Private this As TFinder

Public Property Get Hotels() As Collection
    Set Hotels = this.Hotels
End Property

Private Sub Class_Initialize()
    Set this.Hotels = New Collection
End Sub

Private Sub Class_Terminate()
    Set this.Hotels = Nothing
End Sub

  • 多态-Implements可用于实现抽象接口(以及具体的类),然后您可以针对ISomething抽象编写代码,该抽象也可以是FooBar(假定FooBar都实现了ISomething) -并且所有需要查看的代码都是ISomething.方法重载是VBA缺少的语言功能,但是重载与多态无关,即 the能够针对不同的基础形式(数据类型)呈现相同的界面 .

  • Polymorphism - Implements lets you implement abstract interfaces (and concrete classes, too), and then you can write code against an ISomething abstraction that can just as well be a Foo or a Bar (given Foo and Bar both implement ISomething) - and all the code ever needs to see is ISomething. Method overloading is a language feature that VBA lacks, but overloading has nothing to do with polymorphism, which is the ability to present the same interface for differing underlying forms (data types).

    这是应用的多态性的一个示例-LogManager.Register方法很高兴与实现ILogger接口的任何对象一起使用;在这里,DebugLoggerFileLogger-该接口的两个截然不同的实现正在注册;稍后调用LogManager.Log(ErrorLevel, Err.Description)时,这两个实现将各自做自己的事情; DebugLogger将输出到 immediate 工具窗口,并且FileLogger会将条目写入指定的日志文件:

    Here's an example of applied polymorphism - the LogManager.Register method is happy to work with any object that implements the ILogger interface; here a DebugLogger and a FileLogger - two wildly different implementations of that interface, are being registered; when LogManager.Log(ErrorLevel, Err.Description) is invoked later, the two implementations will each do their own thing; DebugLogger will output to the immediate toolwindow, and FileLogger will write an entry into a specified log file:

    LogManager.Register DebugLogger.Create("MyLogger", DebugLevel)
    LogManager.Register Filelogger.Create("TestLogger", ErrorLevel, "C:\Dev\VBA\log.txt")
    

  • 继承-VBA不允许您派生类型另一个:不支持继承.

  • Inheritance - VBA does not let you derive a type from another: inheritance is not supported.

    现在的问题是,不支持继承的语言是否可以被限定为面向对象"?事实证明,组成通常比继承更可取,其中有一些警告.而且VBA可以让您组成对象以符合您内心的需求.

    Now the question is, can a language that doesn't support inheritance be qualified as "object-oriented"? It turns out composition is very often preferable to inheritance, which has a number of caveats. And VBA will let you compose objects to your heart's content.

    VBA是OOP语言吗?

    鉴于所有遗漏的是继承,并且这种组合比继承更可取,我很想回答是".之前,我已经编写了完整的OOP VBA代码(带有工作单元和存储库的Model-View-Presenter,有人吗?),我不会用支持继承的真正的OOP"语言编写任何不同的东西.

    Given all that's missing is inheritance, and that composition is preferable to inheritance, I'm tempted to answer "Yes". I've written full-blown OOP VBA code before (Model-View-Presenter with Unit-of-Work and Repository, anyone?), that I wouldn't have written any differently in a "real OOP" language that supports inheritance.

    以下是所有100%VBA的示例:

    Here are a few examples, all 100% VBA:

    • Full-blown OOP Battleship game with Model-View-Controller (MVC) architecture
    • A reusable progress indicator
    • Model-View-Presenter pattern
    • UnitOfWork with Repository pattern
    • Polymorphic logger
    • Automagic Unit Testing framework

    最后一个链接中的代码最终移植到C#,并迅速演变为 VBA IDE的COM加载项为您提供重构,更好的导航,代码检查和其他工具.

    The code in this last link was eventually ported to C#, and quickly evolved into a COM add-in for the VBA IDE that gives you refactorings, better navigation, code inspections, and other tools.

    VBA的局限性与您设定的一样.

    VBA is only as limiting as you make it.

    这篇关于VBA是OOP语言吗,它支持多态吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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