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

时间:2022-09-11 20:54:52

Classes in .net like List and Dictionary can be indexed directly, without mentioning a member, like this:

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

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

How do I make a class that can be indexed like that?

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

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

1 个解决方案

#1


8  

You need to provide an indexer (C# terminology) or default property (VB terminology). Example from the MSDN docs:

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

VB: (myStrings is a string array)

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    

And C# syntax:

和C#语法:

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

#1


8  

You need to provide an indexer (C# terminology) or default property (VB terminology). Example from the MSDN docs:

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

VB: (myStrings is a string array)

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    

And C# syntax:

和C#语法:

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