How to attach event handler to an event using reflection?
Date : March 29 2020, 07:55 AM
this one helps. I think your code is failing because the HandleRfqSendComment is private. Instead you could directly create a delegate to that method, without passing its name to CreateDelegate. You would then need to convert the delegate to the required type, using the following method : public static Delegate ConvertDelegate(Delegate originalDelegate, Type targetDelegateType)
{
return Delegate.CreateDelegate(
targetDelegateType,
originalDelegate.Target,
originalDelegate.Method);
}
EventInfo eventInfo = rfqWindowManager.GetType().GetEvent("SendComment");
Action<object, object> handler = HandleRfqSendComment;
Delegate convertedHandler = ConvertDelegate(handler, eventInfo.EventHandlerType);
eventInfo.AddEventHandler(rfqWindowManager, convertedHandler);
|
How to do reflection without System.Reflection? i.e. build custom reflection classes?
Tag : .net , By : Guy Kastenbaum
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , You can simply take a look at the source of Mono.Cecil.
|
Binding an event handler to any type of event using reflection
Tag : chash , By : user119605
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I have some code where I need to dynamically bind events to an event handler: , Here is one way to do it: First create this helper class: public class HandlerHelper<T> where T : EventArgs
{
private readonly EventHandler m_HandlerToCall;
public HandlerHelper(EventHandler handler_to_call)
{
m_HandlerToCall = handler_to_call;
}
public void Handle(object sender, T args)
{
m_HandlerToCall.Invoke(sender, args);
}
}
var event_handler = new EventHandler((s, args) =>
{
// More awesomeness here...
});
foreach (var event_name in event_names)
{
var event_info = control.GetType().GetEvent(event_name);
var event_handler_type = event_info.EventHandlerType;
var event_args_type = event_handler_type.GetMethod("Invoke").GetParameters()[1].ParameterType;
var helper_type = typeof(HandlerHelper<>).MakeGenericType(event_args_type);
var helper = Activator.CreateInstance(helper_type, event_handler);
Delegate my_delegate = Delegate.CreateDelegate(event_handler_type, helper, "Handle");
event_info.AddEventHandler(button, my_delegate);
}
void Handle(object sender, MouseEventArgs args)
|
Why can't I get the event handler of a LinkButton's event using reflection?
Date : March 29 2020, 07:55 AM
|
C# Reflection Programmatic Event Handlers with Custom Event Args
Tag : chash , By : Cesar Sanz
Date : March 29 2020, 07:55 AM
|