我经常定义一个类,我还定义了另一个类,它只是另一个类的集合。为此,我发现最简单的方法是将另一个类定义为Inherits List(Of Type)。我定义集合类的原因是为集合添加额外的功能。以下面的代码为例。
Class Car
Property Name As String
Property Year As Short
Property Model As String
End Class
Class CarCollection
Inherits List(Of Car)
Overloads Sub Add(ByVal Name As String, ByVal Year As Short, ByVal Model As String)
Dim c As New Car
c.Name = Name
c.Year = Year
c.Model = Model
Add(c)
End Sub
End Class
现在,如果我声明一个CarCollection变量,我怎样才能通过名称或索引值引用Car,这就是.NET看起来像集合的方式。以.NET ToolStripItemCollection为例。您可以通过以下两种方式引用其中的项目: MyCollection的(2) MyCollection的( “MyItemName”)
我的问题当然是如何定义我自己的集合,以便我可以通过索引或名称来引用它。现在我只能通过索引来引用它。
答案 0 :(得分:6)
您可以使用KeyedCollection
:
Imports System.Collections.ObjectModel
Public Class CarCollection
Inherits KeyedCollection(Of String, Car)
Protected Overrides Function GetKeyForItem(ByVal item As Car) As String
Return item.Name
End Function
End Class
答案 1 :(得分:3)
您可以重载项目:
'''<summary>
'''Gets or sets a Car object by name.
'''</summary>
Public Default Property Item(ByVal name As String) As Car
Get
'Return the Car with the specified name
End Get
Set(ByVal value As Car)
'Set the Car with the specified name
End Set
End Property
答案 2 :(得分:1)
您可以尝试继承System.Collections.Generic.Dictionary而不是List,当您添加时,也设置密钥。
答案 3 :(得分:1)
让SortedDictionary看一下......就像这样:
Public Class Car
Property Name As String
End Class
Public Class CarCollection
Inherits SortedDictionary(Of String, Car)
'Extend, override as needed, adding in your indexer property
Public Default ReadOnly Property Item(index As Integer) As Car
Get
Return Me.Values.ElementAt(index)
End Get
End Property
End Class
然后你可以像这样使用它:
Dim collection As New CarCollection()
collection.Add("YourNameHere", New Car())
collection("YourNameHere")
答案 4 :(得分:0)
System.Collections.Generic.SortedList集合允许您按索引(通过Keys
和Values
属性)和按键访问项目。