简体   繁体   中英

Determine sender object from event handler

I am using a class raising an event that doesn't contain in the signature of it's event handler a parameter for the sender object.

How can I, from the event handler, determine which object raised the event? how do I get a reference to this object? Can it be done using reflection?

Thanks in advance.

The best way I can think to do this is by using something like the Adapter Pattern. You would basically create a class inside your code that wraps the COM class you're building, which contains its own event that can provide more detailed information. Each instance of your class would create its own instance of the COM class, handle the COM events, and raise its own events to the rest of your code. So, you don't know exactly which COM class is raising the event, but you do know which of your own class instances it is.

But, this type of solution would heavily depend on exactly what you're trying to accomplish. If you're just trying to get better debug information, this is a good route to take, but if you're trying to wire together parts of someone else's library, there are many situations in which this wouldn't accomplish anything.

public class MyClass
{
   private COMClass instance;
   public event EventHandler<BetterEventArgs> MyBetterEvent;

   public MyClass()
   {
      instance.event += new EventHandler(Handle_COM_event); // ... or whatever
   }

   public void Handle_COM_event(EventArgs)
   {
      if(MyBetterEvent != null) MyBetterEvent(this, new BetterEventArgs());
   }

}

MSDN论坛或Google“ C#动态转换或转换”中尝试此操作

You can either use drharris' solution which seems more general and "clearer" or you can use anonymous delegates:

MyComClass cl = new MyComClass();

cl.MyEvent += new MyComClassDelegate(delegate(MyEventArgs args){ RealHandler(cl, args);})

Now your RealHandler will receive the original arguments and the object that raised the event.

This is not something one wants to type a lot but it might be an alternative if you only have a few places where you create the classes and add the event handlers.

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