How to know how many event handlers for an event?
I want a way to execute the following code:
// if (control.CheckedChanged.Handlers.Length == 0)
{
control.CheckedChanged += (s, e) =>
{
// code;
}
}
Note: this code is out side the control class.
Thanks开发者_运维知识库 in advance.
You can't, because only the type that exposes the event has access to the actual delegate. From within the control, you could do something like that:
if (MyEvent!= null)
{
EventHandler[] handlers = (EventHandler[])MyEvent.GetInvocationList();
foreach(EventHandler handler in handlers)
{
...
}
}
Or, for what you're trying to do:
if (CheckedChanged == null)
{
CheckedChanged += (s, e) =>
{
// code;
}
}
My answer is more of a comment for Thomas Levesque, but I can't comment yet, so here goes nothing. I find this area of C# a little ugly, since there's a possibility to introduce race conditions - i.e. different threads may race and you may enter the if
statement with CheckedChanged != null
if (CheckedChanged == null)
{
CheckedChanged += (s, e) =>
{
// code;
}
}
You should either lock this code, but in many cases you will find yourself writing code like this
//Invoke SomeEvent if there are any handlers attached to it.
if(SomeEvent != null) SomeEvent();
But SomeEvent may be nulled in the process, so it would be safer to write something like this
SomeEVentHandler handler = SomeEvent;
if (handler != null) handler();
...just to be extra safe.
精彩评论