vba - 为什么有些类的名字前面有一个 "I"?

标签 vba

我正在使用 Visual Basic 98 中的一些遗留代码,并且有几个类的名称前面带有“I”。然而,大多数类没有这个名称。

这是 IXMLSerializable.cls 文件的内容。

' Serialization XML:
'       Create and receive complete split data through XML node
Public Property Let SerializationXML(ByVal p_sXML As String)
End Property
Public Property Get SerializationXML() As String
End Property

Public Property Get SerializationXMLElement() As IXMLDOMElement
End Property

最佳答案

请注意 VBA支持接口(interface),就像 C#/VB.NET做(几乎)。接口(interface)是在VBA 中提供继承机制的唯一方法。 .

By convention interfaces start their name with the capital letter I.



这是一个示例接口(interface)声明,它声明一个对象必须定义一个名称属性

[File: IHasName.cls, Instancing: PublicNotCreatable] 
Option Explicit

Public Property Get Name() As String
End Property

如您所见,不需要实现。

现在创建一个对象,该对象使用该接口(interface)来宣传它包含一个名称属性。当然,关键是有多个类使用一个接口(interface)。

[File: Person.cls, Instancing: Private]
Option Explicit
Implements IHasName

Private m_name As String

Private Sub Class_Initialize()
    m_name = "<Empty>"
End Sub

' Local property
Public Property Get Name() as String
    Name = m_name
End Property

Public Property Let Name(ByVal x As String)
    m_name = x
End Property

' This is the interface implementation that relies on local the property `Name` 
Private Property Get IHasName_Name() As String
    IHasName_Name = Name
End Property

包含 Implements 后,为了方便 UI声明您可以从顶部选择接口(interface)属性

scr

要使用上述代码,请使用以下测试,该测试调用一个函数,该函数可以采用任何实现 IHasName 的对象.

[File: Module1.bas]
Option Explicit

Public Sub TestInterface()

    Dim target As New Person
    target.Name = "John"

    GenReport target
    ' This prints the name "John".
End Sub

Public Function GenReport(ByVal obj As IHasName)
    Debug.Print obj.Name
End Function

关于vba - 为什么有些类的名字前面有一个 "I"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56461992/

相关文章:

excel - 范围类的自动调整方法失败(运行时错误 1004)

excel - VBA 函数根据列值复制到新行

Excel VBA 通过连续单击单元格/文本按多个条件排序

vba - 在不同的工作簿中捕捉事件

vba - 如何让 VBA 在单击用户窗体中的任何复选框时运行?

excel - 将 Excel 2007 VBA 转换为 Excel 2003

c# - 从 Excel VBA 启动 TransactionScope?

algorithm - VBA 中的递归、多个基本情况

regex - 使用 VBA 从文本文件写入 Excel 时保留 "columns"

VBA:嵌套字典是一个很好的解决方案吗?