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

时间:2009-12-23 12:17:01

标签: .net arrays list

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

Dim MyList as New List (of integer)
...
MyList(5) 'get the sixth element
MyList.Items(5) 'same thing

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

Dim c as New MyClass
...
c(5) 'get the sixth whatever from c

1 个答案:

答案 0 :(得分:8)

您需要提供索引器(C#术语)或默认属性(VB术语)。 MSDN docs的示例:

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    

和C#语法:

public string this[int index]
{
    get { return myStrings[index]; }
    set { myStrings[index] = vaue; }
}