热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

VBA是一种OOP语言,它支持多态性吗?-IsVBAanOOPlanguage,anddoesitsupportpolymorphism?

IamactuallyworkingonmyfirstVBAproject.(comefromC++)我正在做我的第一个VBA项目。(来自C++)Iwouldlik

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

我正在做我的第一个VBA项目。(来自C + +)

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

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

My problem is:

我的问题是:

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.

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

Some of them propose a workaround using the keyword Implements.

他们中的一些人提出了使用关键字实现的解决方案。

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.

2 -我还发现了一些像这样的网页,解释了如何使用继承、重写、可重写、MustOverrides等关键字在VBA中执行OOP和多态性。

So my question is :

我的问题是

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

VBA是一种OOP语言,它支持多态性吗?

2 个解决方案

#1


60  

OOP is sitting on 4 "pillars":

OOP坐在4根柱子上:

  • check 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).

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

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

    下面是用VBA编写的一个演示抽象的过程示例:

    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
    

    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.

    很容易就能一眼看出这个测试过程的作用,因为抽象级别非常高:实现细节被抽象为更专门化的对象和方法。

  • check 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.

    封装——类可以有属性公开的私有字段;可以将类设置为PublicNotCreatable,有效地将类型公开到其他VBA项目中——只需稍加努力(通过导出类模块,在您喜欢的文本编辑器中打开它,手工编辑类属性,并重新导入模块),就可以实现实际的只读类型。没有参数化构造函数这一事实是无关的——只需编写一个工厂方法,该方法接受您喜欢的所有参数并返回一个实例。这是COM, COM喜欢工厂。

    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:

    下面是一个例子,说明上面代码片段中的HotelFinder类如何封装一个集合对象,并仅通过属性Get accessor公开它——这个类之外的代码无法设置这个引用,它被封装:

    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
    
  • check 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).

    多态性——实现允许您实现抽象接口(和具体类),然后你可以编写代码对一个称为抽象,一样可以Foo或酒吧(鉴于Foo和Bar实现称为)——和所有的代码需要看到的是称为。方法重载是VBA所缺乏的一种语言特性,但是重载与多态性无关,多态性是为不同的底层表单(数据类型)提供相同接口的能力。

    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:

    这里有一个应用多态的例子——日志管理器。寄存器方法乐于与任何实现ILogger接口的对象一起工作;这里注册了一个调试程序和一个FileLogger——该接口的两个完全不同的实现;当LogManager。稍后将调用Log(ErrorLevel, error . description),两个实现将各自执行自己的操作;DebugLogger将输出到即时工具窗口,FileLogger将把一个条目写入指定的日志文件中:

    LogManager.Register DebugLogger.Create("MyLogger", DebugLevel)
    LogManager.Register Filelogger.Create("TestLogger", ErrorLevel, "C:\Dev\VBA\log.txt")
    
  • nope 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会让你根据自己的内心内容创作物品。

Is VBA an OOP language?

VBA是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.

考虑到所缺少的只是继承,而组合比继承更可取,我忍不住要回答“是”。我以前编写过完整的OOP VBA代码(有工作单元和存储库的模型-视图演示程序吗?),我不会用支持继承的“真正的OOP”语言编写任何不同的代码。

Here are a few examples, all 100% VBA:

以下是一些100% VBA的例子:

  • A reusable progress indicator
  • 一个可重用的进度
  • Model-View-Presenter pattern
  • Model-View-Presenter模式
  • UnitOfWork with Repository pattern
  • UnitOfWork库模式
  • Polymorphic logger
  • 多态记录器
  • Automagic Unit Testing framework
  • 自动单元测试框架

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.

最后一个链接中的代码最终被移植到c#中,并迅速发展为VBA IDE的COM外接程序,它为您提供重构、更好的导航、代码检查和其他工具。

VBA is only as limiting as you make it.

VBA只在你做的时候限制。

#2


4  

The short answers are no and no.

简短的回答是“不”和“不”。

VBA is object based, allowing you to define classes and create instances of objects but it lacks the features that would normally be associated with a fully fledged OOP language, for example:

VBA是基于对象的,允许您定义类并创建对象实例,但它缺乏与成熟的OOP语言相关联的特性,例如:

  • Encapsulation and abstraction: VBA provides this to an extent. Classes can be kept private with public interfaces defined, however there is no provision for constructors within classes. Classes have a Class_Inititalize event which can do some construction but cannot take arguments. Passing arguments would require a public factory function workarounds are still required to create a constructor-style design pattern.
  • 封装和抽象:VBA在一定程度上提供了这一点。类可以通过定义的公共接口保持私有,但是类中没有构造函数的规定。类有一个Class_Inititalize事件,该事件可以执行某些构造,但不能接受参数。传递参数需要一个公共工厂功能工作区,仍然需要创建一个构造样式的设计模式。
  • Inheritance: Doesn't really exist in VBA but can be almost replicated
  • 继承:在VBA中并不存在,但几乎可以复制
  • Polymorphism: Can be achieved to an extent through interfaces (using Implements) although the ability to overload functions (for example) doesn't exist and each "overload" would technically require a unique function name. You can work around this by passing in an object as the only parameter to a function or sub and vary the procedure depending on the values of the properties.
  • 多态性:可以通过接口(使用实现)在一定程度上实现,尽管重载函数(例如)的能力并不存在,而且每个“重载”在技术上都需要一个唯一的函数名。您可以通过将对象作为唯一的参数传递给函数或子函数来解决这个问题,并根据属性的值更改过程。

So while you can work with objects to an extent and MS Office applications are based around an object model, VBA is not truely an Object Oriented language. Polymorphism cannot be achieved to the extent that you would be familiar with in C++.

因此,虽然您可以在一定程度上使用对象,MS Office应用程序基于对象模型,但VBA并不是真正的面向对象语言。多态不能达到您在c++中所熟悉的程度。


推荐阅读
author-avatar
exu8145079
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有