【发布时间】:2012-07-11 00:19:56
【问题描述】:
我有一个 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 中?
注意
示例中显示的类和事件是从现实生活中的应用程序简化而来的,但假设它们显示了应用程序的确切结构。在最后一个继承的类中引发事件是必须的。
【问题讨论】:
-
为什么要从子类调用
OnPreInsertItem(EventArgs.Empty)?当您执行MyBase.InsertItem(index, item)时,它已经被调用了。 -
这里我展示了一个简化的例子。在实际应用中,大量数据在事件数据中传递。所以必须在每个继承的类(即 MyColSubClass)中调用事件。
标签: .net vb.net events inheritance overriding