我有一个控件集合,在 foreach 循环中注册了一个 CommandEventhandler:
foreach (Control control in myObject.Controls)
{
control.Command += new CommandEventHandler(myEventHandler);
}
集合中的某些控件不应注册处理程序。
有没有办法阻止 Button 注册 CommandEventHandler ?
如果您有权访问定义事件的代码,您可以在“add”访问器中进行检查,该访问器将决定是否添加处理程序。它看起来像下面这样:
private EventHandler _myEvent;
public event EventHandler MyEvent
{
[MethodImpl(MethodImplOptions.Synchronized)]
add
{
if (CanAddEventHandler()) // <- that's yours to implement
{
_myEvent = (EventHandler)Delegate.Combine(_myEvent, value);
}
}
[MethodImpl(MethodImplOptions.Synchronized)]
remove
{
_myEvent = (EventHandler)Delegate.Remove(_myEvent, value);
}
}