是否存在存储由字符串键或整数索引索引的数据的类型?

Mas*_*low 5 .net collections

List(Of T)存储由整数索引的数据Dictionary(Of String, T)存储通过字符串索引的 数据

是否有类型或通用或专门的东西,让我可以T通过索引或名称访问数组?

Meh*_*ari 7

我认为System.Collections.Specialized.OrderedDictionary这就是你要找的东西.


Joe*_*orn 5

如果你的"名字"很容易从你的"T"确定,我建议KeyedCollection.

它的工作方式类似于List,您可以按索引查找项目.但它也像字典一样工作,因为它在内部使用Dictionary来将名称(键)映射到适当的索引,并为您的键类型提供索引器.


你问它是如何知道密钥的用途. KeyedCollection是一个你必须继承的抽象类.幸运的是,这很容易做到.你需要重载的唯一方法是GetKeyForItem().这个方法就是你问题的答案.例如,拿这个简单的类:

Public Class MyClass
    Public UniqueID As Guid
    Public OtherData As String
End Class
Run Code Online (Sandbox Code Playgroud)

您可以像这样实现KeyedCollection:

Public Class MyClassCollection
    Inherits KeyedCollection(Of Guid, MyClass)

    Public Overrides Function GetKeyForItem(ByVal item As MyClass) As Guid
        Return item.UniqueID
    End Function
End Class
Run Code Online (Sandbox Code Playgroud)

这里的所有都是它的.您现在拥有一个可以像字典或列表一样工作的集合.当你可以使用泛型或其他接口来避免将类绑定到特定类型时,它会更加强大.