简体   繁体   中英

Check if a specific event handler method already attached

Related to this question, Check if an event already exists

but the difference is I just want to know if a particular method is attached to the event. So there may be other methods attached, but I just want to know if a particular one exists.

My environment is C# in dotnet 4.0.

Eg

Event += MyMethod1;
Event += MyMethod2;

// Some code
if (MyMethod1IsAttachedToEvent())
{
    // Achieved goal
}

Is this possible?

No. You cannot.

The event keyword was explicitly invented to prevent you from doing what you want to do. It makes the delegate object for the event inaccessible so nobody can mess with the events handlers.

Source : How to dermine if an event is already subscribed

foreach ( Delegate existingHandler in this.EventHandler.GetInvocationList() )
{
    if ( existingHandler == prospectiveHandler )
    {
          return true;
    }
}

loop through the delegates using the GetInvocationList method.

Event.GetInvocationList().Any(x => x.Method.Name.Equals("yourmethodname"));

Late answer here. I believe Parimal Raj answer is correct, as I could not find a way to directly access the events. However, here are two methods I created to get around this:

  1. Delete before adding. If the method isn't there, I did not receive an error trying to delete the nonexistant method. This way you can insure the invocation list calls method1 only once.

     Event -= MyMethod1; Event += MyMethod1;
  2. The objects you are adding an event to may have a .Tag property. You can use the Tag to store info about the methods you already added. Here I only have one method, so I just need to check if Tag is null. But more complicated scenarios can be handled this way:

     if(control.Tag == null) { //ony added once, when tag is null control.TextChanged += new EventHandler(validate); control.Tag = new ControlTag(); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM