如何创建一个可以像.net中的列表一样编入索引的类?

Eya*_*yal 0 .net arrays list

.net中的类如List和Dictionary可以直接编入索引,而不提及成员,如下所示:

Dim MyList as New List (of integer)
...
MyList(5) 'get the sixth element
MyList.Items(5) 'same thing
Run Code Online (Sandbox Code Playgroud)

如何创建一个可以像这样索引的类?

Dim c as New MyClass
...
c(5) 'get the sixth whatever from c
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 8

您需要提供索引器(C#术语)或默认属性(VB术语).来自MSDN文档的示例:

VB :( myStrings是一个字符串数组)

Default Property myProperty(ByVal index As Integer) As String
    Get
        ' The Get property procedure is called when the value
        ' of the property is retrieved.
        Return myStrings(index)
    End Get
    Set(ByVal Value As String)
        ' The Set property procedure is called when the value
        ' of the property is modified.
        ' The value to be assigned is passed in the argument 
        ' to Set.
        myStrings(index) = Value
    End Set
End Property    
Run Code Online (Sandbox Code Playgroud)

和C#语法:

public string this[int index]
{
    get { return myStrings[index]; }
    set { myStrings[index] = vaue; }
}
Run Code Online (Sandbox Code Playgroud)