VB.Net Com类继承

3
我有一个情况,即当通过VBA访问接口时,VB.Net COM类未继承可访问父类的函数。
也就是说,我有一个VB.Net COM类(myParent)和一个VB.Net COM子类(myChild)。
我已经搜索并在这里找到了类似的内容:Exposing inherited members of a COM vb.net class,但“尝试这个”解决方案似乎不存在?
<ComClass(MyParent.ClassId, MyParent.InterfaceId, MyParent.EventsId)>
Public Class MyParent

#Region "COM GUIDs"
    Public Const ClassId As String = "386e628c-872b-41ee-abb2-d2a5dfb4e51e"
    Public Const InterfaceId As String = "f4b194f1-9dc9-4f37-93d8-57cb97e05593"
    Public Const EventsId As String = "4320826d-a02c-4360-b8b5-4c98569c2b2e"
#End Region

    Public Sub New()
        MyBase.New()
    End Sub


    Public Function parent_hello_world() As Boolean
        MsgBox("Hello from Parent")
        Return True
    End Function

End Class

<ComClass(MyChild.ClassId, MyChild.InterfaceId, MyChild.EventsId)>
Public Class MyChild
    Inherits MyParent

#Region "COM GUIDs"
    Public Const ClassId As String = "65674d29-7bb7-447e-8282-47b9873cec4a"
    Public Const InterfaceId As String = "cbcdfb17-c8b9-42e2-bed7-b516b9df6111"
    Public Const EventsId As String = "22a8959c-7594-4584-b53d-a087246be623"
#End Region

    Public Sub New()
        MyBase.New()
    End Sub


    Public Function child_hello_world() As Boolean
        MsgBox("Hello from Child")
        Return True
    End Function

End Class

以下代码(在VBA中执行时)会失败:
Sub test_me()
    Dim tip As New TestInheritance.MyParent
    Dim tic As New TestInheritance.MyChild
    tip.parent_hello_world()  'this works - directly from parent

    tic.child_hello_world()  'this works - child function
    tic.parent_hello_world()  'throws an error - not accessible?

End Sub

除了需要在子类中重新定义接口之外,是否有其他解决方案?
非常感谢。

1
为两个类定义接口,并让子接口实现基础接口。COM coclasses几乎总是接口实现的集合 - 显式创建它们,而不是依赖编译器来为您完成。 - Comintern
1个回答

2
COM在幕后使用超纯接口为基础的范例。你需要与其映射到VB.NET和VBA语言的方式进行斗争。在VB.NET方面,实现继承是一个问题,编译器会将你的类重写为实现两个接口。默认接口映射了类的成员,第二个非默认接口映射了继承的成员。
这对于VBA来说就是个问题,因为它根本没有直接支持接口。你只能直接使用默认接口,获取对另一个接口的引用需要使用“Set”关键字。像这样:
Dim child As New TestInheritance.MyChild
child.child_hello_world
Dim parent As TestInheritance.MyParent
Set parent = child
parent.parent_hello_world

那是可以的,但肯定没有什么值得热情的理由。最大的问题是这段代码完全是不可发现的。你提出这个问题的原因是,在 VBA 文本编辑器的自动补全对话框中,没有任何提示可以让你知道这个方法是可行的。你必须编写一个手册来告诉你的客户端程序员们关于这个方法的使用。而如果客户端程序员更喜欢后期绑定,则完全无法使用此方法。
您可以考虑的一件事是直接通过属性公开基类,这是您将编写的最短的代码之一:
Public ReadOnly Property Parent As MyParent
    Get
        Return Me
    End Get
End Property

现在在VBA中高度可发现,你不会有任何问题到达:
Dim child As New TestInheritance.MyChild
child.child_hello_world
child.parent.parent_hello_world

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接