在VBA中实现一个接口时,实现的功能是需要私有的还是公共的?

问题描述 投票:1回答:1

我在这里阅读了关于创建类工厂的资料。https:/rubberduckvba.wordpress.com20180424factories-parameterized-object-initialization。 我很困惑,为什么他们要把实现的函数做成私有的,难道我们不希望它们是公共的,这样我们就可以访问它们吗?

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

另外,为什么你需要为接口中的公共变量提供get和let属性?

excel vba oop interface implements
1个回答
6
投票

他们应该是 Private.

因为在VBA中,接口的工作方式是这样的:在VBA中的 Public 的成员定义其 默认接口. 这意味着公众成员的 Class1 定义成员 Class2 必须实施,如果它 Implements Class1.

所以如果你做 Class1_DoSomething public,那么你就会在默认的 Class2而这... ... 一点也不好看。

你用什么接口访问一个对象,是由你如何声明它决定的。

Dim thing As Class1
Set thing = New Class1

如果 thing或实施 Class1的默认接口所暴露的所有成员,那么这个声明之后的代码就可以调用由 Class1 (即其公众成员)。

如果 Class1 实施 ISomething 然后我们这样声明。

Dim thing As ISomething
Set thing = New Class1

现在我们要使用的成员是由公共成员定义的成员 ISomething 类接口。

当你实现一个接口或处理事件时,千万不要手动键入签名;而是从代码窗格的左上角下拉中挑选接口(或事件提供者),然后从右上角下拉中挑选一个成员:VBE会自动创建具有正确签名的正确过程,而且它总是会是一个 Private 成员--经验法则,在VBA中,任何名称中带有下划线的东西都不能成为 Public


至于为什么你必须提供 GetLet 你在接口类中定义的公共字段(变量)的访问器...。字段是实现细节,它们不应该是 Public 首先。对象暴露出 属性,而不是字段--为实现类的私有内部状态保留字段。

原因是技术上的。VBA代码被编译到一个COM类型的库中,这个库看到你的公有变量就会说 "这必须是一个PUT和一个GET方法",因此实现该接口的VBA代码需要为每一个公有字段实现一个属性,因为公有字段会被编译成属性。

这对于在类模块上暴露公有字段的做法确实有有趣的影响(反正打破了封装与编译成属性!),但这是另一个讨论。

© www.soinside.com 2019 - 2024. All rights reserved.