如何在VB.NET中声明COM可见的默认索引属性?

如何在VB.NET中声明一个默认的索引属性,以便它可以从VBScript调用?

我试过这个

<DispId(0)> _
Public ReadOnly Property Item(ByVal idx As Integer) As ...

但是VBScript会返回错误消息

参数数量错误或属性分配无效
错误代码800A01C2

如果我从VB.NET公开普通属性(非索引),则不会发生此错误.

这是一个示例:

“Class1.vb:

  Public Class Class1
    Public ReadOnly Property Dogs() As Dogs
        Get
            Return New Dogs()
        End Get
    End Property
  End Class

“Dogs.vb:

  Imports System.Runtime.InteropServices

  Public Class Dogs
    <DispId(0)> _
    Public ReadOnly Property Item(ByVal idx As Integer) As Dog
        Get
            Return New Dog
        End Get
    End Property
  End Class

“Dog.vb:

  Public Class Dog
    Public ReadOnly Property Name() As String
        Get
            Return "Fido"
        End Get
    End Property
  End Class

VBScript中:

  Set obj = CreateObject("FmuComTest.Class1")

  MsgBox obj.Dogs.Item(0).Name   ' this works

  MsgBox obj.Dogs(0).Name        ' error message

访问默认的索引属性Dogs.Item(idx)会导致错误消息.

最佳答案 这篇MSDN博文可能会对这个问题有所了解.似乎VBScript& COM对于如何调用默认值很挑剔.

http://blogs.msdn.com/ericlippert/archive/2005/08/30/458051.aspx

点赞