重载是一个完全不同的概念。从本质上讲,重载允许您拥有多个Add()
andRemove()
方法,同时覆盖方法“替换”原始行为。阴影介于两者之间。阴影“隐藏”了原始行为,但您仍然可以通过转换为基本类型来访问基本方法。
一般来说,如果你可以覆盖它,你就不会隐藏它。除非您有非常具体的理由这样做。
请注意,您不能同时覆盖和隐藏同一个成员。但是,例如,您可以覆盖和重载原始Add()
方法。
编辑
您不能覆盖该Add()
方法,但可以覆盖OnAddingNew()
. 同样,您不能覆盖Remove()
,但可以覆盖RemoveItem()
。我不知道这个类的细节,但我怀疑它在幕后Remove()
使用RemoveItem()
。
您的实现可能看起来像这样:
Imports System.ComponentModel
Imports System.Collections.ObjectModel
Public Class DeviceUnderTestBindingList
Inherits BindingList(Of DeviceUnderTest)
Private Sub New()
MyBase.New()
End Sub
#Region "Add()"
Protected Overrides Sub OnAddingNew(e As AddingNewEventArgs)
Dim newDevice As DeviceUnderTest = DirectCast(e.NewObject, DeviceUnderTest)
Try
If (Not IsValidEntry(newDevice)) Then ' don't add the device to the list
Exit Sub
End If
' (optionally) run additional code
DoSomethingWith(newDevice)
Finally
MyBase.OnAddingNew(e)
End Try
End Sub
Private Function IsValidEntry(device As DeviceUnderTest) As Boolean
' determine whether the specified device should be added to the list
Return True Or False
End Function
Private Sub DoSomethingWith(newDevice As DeviceUnderTest)
' This is where you run additional code that you would otherwise put in the 'Add()' method.
Throw New NotImplementedException
End Sub
#End Region ' Add()
#Region "Remove()"
Public Shadows Function Remove(device As DeviceUnderTest) As Boolean
Try
RemoveItem(IndexOf(device))
Catch
Return False
End Try
Return True
End Function
Protected Overrides Sub RemoveItem(index As Integer)
MyBase.RemoveItem(index)
End Sub
#End Region ' Remove()
End Class