有些人建议从 Collection 继承来获取集合类。其他一些人建议从头开始创建类和实现接口。我想了解何时使用一个而不是另一个。
我看到当我使用时:
class MyCollection
Inherits Collection(Of SomeObject)
我有可能为每个等添加,插入,这可能是因为Collection<T> uses internally List<T>
但是,如果我只是这样做:
class MyCollection : IList(Of SomeObject), IEnumerable<SomeObject>, IEnumerable(Of SomeObject)
myList As List(Of SomeObject)
我也可以实现这样的事情Add(), Remove(), for each
使用 Collection(Of T) 是不是很好,因为它已经包含所有这些实现的接口和内部 List(Of T) 而不是自己在 self 类中从头开始实现所有接口?这是人们建议继承的重点COllection(Of T)吗?
编辑(进一步讨论):
Public Class Merge
Property Size As Integer
Property Datee As Date
Property Min As Integer
Property Max As Integer?
Property Value As Double
Public Sub New(min As Integer, max As Integer?, value As Integer)
Me.Min = min
Me.Max = max
Me.Value = value
End Sub
End Class
Public Enum SortCriteria
MinThenMax
MaxThenMin
End Enum
Public Class MergeComparer
Implements IComparer(Of Merge) 'do oddzielnej klasy sortowania obiektu jak tutaj potrzebujemy IComparer a nie IComparable (ten jest bezposrednio na klasie)
Public SortBy As SortCriteria = SortCriteria.MinThenMax
Public Function Compare(x As Merge, y As Merge) As Integer Implements IComparer(Of Merge).Compare
'to be implemented
End Function
End Class
Public Class MergeCollection
Inherits Collection(Of Merge)
Public SortBy As SortCriteria = SortCriteria.MinThenMax
''' <summary>
''' Ovveride because
''' There could be only one item on list which contains Max prop = Nothing
''' </summary>
''' <param name="index"></param>
''' <param name="item"></param>
Protected Overrides Sub InsertItem(index As Integer, item As Merge)
if IsNothing(item.Max)
If Items.Any(Function(myObject) IsNothing(Items.Max)) Then
Return
End If
End If
MyBase.InsertItem(index, item)
End Sub
Public Sub Sort()
Dim allItems = Items.ToArray()
Array.Sort(allItems)
For i = 0 To allItems.GetUpperBound(0)
Items(i) = allItems(i)
Next
End Sub
Public Sub Sort(comparison As Comparison(Of Merge))
Dim allItems = Items.ToArray()
Array.Sort(allItems, comparison)
For i = 0 To allItems.GetUpperBound(0)
Items(i) = allItems(i)
Next
End Sub
Public Sub Sort(comparer As IComparer(Of Merge))
Dim allItems = Items.ToArray()
Array.Sort(allItems, comparer)
For i = 0 To allItems.GetUpperBound(0)
Items(i) = allItems(i)
Next
End Sub
End Class