【问题标题】:Exposing a Collection to a VB6 app through COM Interop通过 COM 互操作向 VB6 应用程序公开集合
【发布时间】:2015-03-21 18:32:34
【问题描述】:

我正在尝试将以下函数添加到我的 COM 类库中,但它无法编译。我相信您不能将集合公开给 COM。我认为通过在我的 VS2013 机器和 VB6 机器上使用 RegAsm 并将 Microsoft.VisualBasic.dll 注册为 tlb 可以工作,但不能。

如果不是,那么将某种对象列表传递给 VB6 应用程序的最佳方式是什么。

    Public Function GetCustomerCollection() As Collection
    Dim collection As New Collection

    Dim c1 As New customer
    c1.Name = "Test Customer1"
    c1.Phone = "(888) 777-9443"
    c1.Balance = 22.58

    Dim c2 As New customer
    c2 .Name = "Test Customer2"
    c2 .Phone = "(888) 433-4423"
    c2 .Balance = 99.99

    collection.Add(c1)
    collection.Add(c2)

    Return collection
End Function

更新
在 VB6 中,我正在尝试这样来检索列表:

Private Sub Form_Load()
Dim demo As New testLibrary.Demo

Dim customerList As Collection
Set customerList = demo.GetCustomerCollection

Label1.Caption = customerList(1)
End Sub

【问题讨论】:

    标签: vb.net com vb6 com-interop


    【解决方案1】:

    不,Microsoft.VisualBasic.Collection 类不是 <ComVisible(True)>。 System.Collections 中的任何 .NET 1.x 接口和集合类都很好。

    COM 方式是只公开接口,所以如果 VB6 代码不应该修改集合,则使用 IEnumerable,如果是,则使用 IList。所以你想这样写:

    Public Function GetCustomerCollection() As System.Collections.IEnumerable
        Dim collection As New List(Of customer)
    
        collection.Add(New customer With {.Name = "Test Customer1", .Phone = "(888) 777-9443", .Balance = 22.58})
        collection.Add(New customer With {.Name = "Test Customer2", .Phone = "(888) 433-4423", .Balance = 99.99})
    
        Return collection
    End Function
    

    如果需要修改,则替换为 IList。

    【讨论】:

    • 感谢您的出色回复,您是否有机会查看我上面的更新并告诉我我在尝试检索集合的 VB6 代码中做错了什么?
    • 你还在使用 Collection 类,不要那样做。
    • 那我该如何找回呢?使用 CreateObject?
    • 如果可能的话,我将如何在我的 VB6 应用程序中检索第一个客户的示例非常好。
    • 我想你只是用它来检索第一个客户的名字Dim objColl As Object: Set objColl = GetCustomerCollection: Debug.Print "First customer name is " & objColl(0).Name 注意第一个客户将是零项
    猜你喜欢
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    相关资源
    最近更新 更多