我有一個MyCol類,它繼承自ObservableCollection(Of T)。它覆蓋InsertItem方法,以這樣一種方式:如何正確覆蓋引發事件的方法
Public Event PreInsertItem As EventHandler(Of EventArgs)
Protected Overridable Sub OnPreInsertItem(e As EventAtgs)
RaiseEvent PreInsertItem(Me, e)
End Sub
Protected Overrides Sub InsertItem(index As Integer, item As T)
OnPreInsertItem(EventArgs.Empty)
MyBase.InsertItem(index, item)
End Sub
正如你可以看到我已經添加了被提出的每一個項目添加到MyCol收集時間的事件。
接着我創建另一個類MyColSubClass,它從MyCol繼承,並且還覆蓋InsertItem方法:
Public Overrides Sub InsertItem(index as Integer, item as T)
OnPreInsertItem(EventArgs.Empty)
' some additional code goes here
MyBase.InsertItem(index, item)
End Sub
的問題是:
現在,當我使用MyColSubClass的一個實例,並添加項目,PreInsertItem事件被引發兩次:第一次在MyColSubClass和比MyCol。
我應該使用什麼設計模式來使PreInsertItem事件只會引發一次:在MyColSubClass中?
N.B.
示例中顯示的類和事件從現實生活應用程序中簡化了,但假設它們顯示了確切的應用程序結構。在最後的繼承類中提高事件是必須的。
爲什麼要從子類調用'OnPreInsertItem(EventArgs.Empty)'?當你執行'MyBase.InsertItem(index,item)'時,它已經被調用了。 – LarsTech 2012-07-11 12:03:43
這裏我展示了一個簡化的例子。在實際應用中,很多數據都在事件數據中傳遞。所以必須在每個繼承的類中調用事件(即MyColSubClass)。 – Dima 2012-07-11 12:08:21