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 sen开发者_如何学JAVAder 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());
}
}
Try this from MSDN forums or otherwise google "C# dynamic cast or casting"
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.
精彩评论