excel - 在 VBA 中实现接口(interface)时,实现的功能需要是私有(private)的还是公有的?

标签 excel vba oop interface implements

我正在阅读有关创建类工厂的内容:https://rubberduckvba.wordpress.com/2018/04/24/factories-parameterized-object-initialization/我很困惑为什么他们将已实现的功能设为私有(private),难道我们不希望它们公开以便我们可以访问它们吗?

VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "Something"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Private Type TSomething
    Bar As Long
    Ducky As String
End Type

Private this As TSomething
Implements ISomething

Public Function Create(ByVal initialBar As Long, ByVal initialDucky As String) As ISomething
    With New Something
        .Bar = initialBar
        .Ducky = initialDucky
        Set Create = .Self
    End With
End Function

Public Property Get Self() As ISomething
    Set Self = Me
End Property

Public Property Get Bar() As Long
    Bar = this.Bar
End Property

Friend Property Let Bar(ByVal value As Long)
    this.Bar = value
End Property

Public Property Get Ducky() As String
    Ducky = this.Ducky
End Property

Friend Property Let Ducky(ByVal value As String)
    this.Ducky = value
End Property

Private Property Get ISomething_Bar() As Long
    ISomething_Bar = Bar
End Property

Private Property Get ISomething_Ducky() As String
    ISomething_Ducky = Ducky
End Property

另外,为什么需要在接口(interface)中为公共(public)变量提供 get 和 let 属性?

最佳答案

它们应该是Private

原因在于接口(interface)在 VBA 中的工作方式:类模块的 Public 成员定义其默认接口(interface)。这意味着 Class1 的公共(public)成员定义了成员 Class2Implements Class1 时必须实现的内容。

因此,如果您将 Class1_DoSomething 公开,那么您将在 Class2 的默认接口(interface)上公开该成员,这......一点也不漂亮。

您使用什么接口(interface)访问一个对象,取决于您如何声明它。

Dim thing As Class1
Set thing = New Class1

如果thing或implementsClass1,那么这个声明之后的代码可以调用默认接口(interface)暴露的所有成员>Class1(即它的公共(public)成员)。

如果 Class1 实现了 ISomething 并且我们这样声明它:

Dim thing As ISomething
Set thing = New Class1

现在我们使用的成员是由 ISomething 类/接口(interface)的公共(public)成员定义的成员。

当你实现一个接口(interface)或处理事件时,你不应该手动输入签名;相反,从代码 Pane 左上角的下拉列表中选择接口(interface)(或事件提供者),然后从右上角的下拉列表中选择一个成员:VBE 自动创建具有正确签名的正确过程,并且它总是Private 成员 - 根据经验,在 VBA 中名称中带有下划线的任何内容都与 Public

无关

至于为什么必须为接口(interface)类上定义为公共(public)字段(/变量)的内容提供 GetLet 访问器...字段是实现细节, 它们从一开始就不应该是 Public 。对象公开属性,而不是字段 - 为实现类的私有(private)内部状态保留字段。

原因是技术性的:VBA 代码被编译成一个 COM 类型库,该库看到您的公共(public)变量并说“这将必须是一个 PUT 和一个 GET 方法”,因此实现该接口(interface)的 VBA 代码需要为每个公共(public)字段实现一个属性,因为公共(public)字段会编译为属性。

这对于在类模块上公开公共(public)字段的做法确实具有有趣的含义(破坏封装 vs 编译为属性!),但这是另一个讨论。

关于excel - 在 VBA 中实现接口(interface)时,实现的功能需要是私有(private)的还是公有的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62430228/

相关文章:

excel - VBscript 找不到 Excel 文件

excel - VBA中的字典是用空键值对创建的

vba - 在 MS Access 中附加链接表时出现运行时错误

c# - 类字段可以密封吗?

c - 如何在 C 中模拟 OO 风格的多态性?

java - 使配置对所有类可用

excel - Excel的 'Dependency-Chain'是增加还是减少?

java - 为什么我的插件中的 Webwork 方法会落入 JIRA 的 ActionSupport 类?

vba - 使用密码命名工作簿

vba - Excel VBA - 使用左函数和查找