C # Reflection Programmatic Args Custom Event Handlers

Here is my problem / scenario

public class TestEventArgs : EventArgs
{
   public int ID { get; set; }
   public string Name { get; set; }
}

public event EventHandler<TestEventArgs> TestClick

How can I bind EventHandler to TestClick using reflection? (obj - instance, Activator.CreateInstance)

EventInfo eventClick = obj.GetType().GetEvent("TestClick");
Delegate handler = Delegate.CreateDelegate(eventClick.EventHandlerType, obj, ????);
eventClick.AddEventHandler(obj, handler);

My problem is that TestEventArgs is declared in an external dll, but ???? Does methodinfo above require a signature in its delegate?

+3
source share
3 answers

I manage to get my code to work following the procedure described below, http://www.pelennorfields.com/matt/2009/03/13/createdelegate-error-binding-to-target-method/

In essence, if I do the following, I get the error message "Error binding to the target method",

FAIL:

EventInfo eventClick = obj.GetType().GetEvent("TestClick");
Delegate handler = Delegate.CreateDelegate(
    eventClick.EventHandlerType, this, "TestClick");
eventClick.AddEventHandler(obj, handler);

SUCCESS:

But when I changed it to:

MethodInfo methodOn_TestClick = this.GetType().GetMethod("TestClick", new Type[] { typeof(object), typeof(EventArgs));

Delegate handler = Delegate.CreateDelegate(
    event_DomClick.EventHandlerType, this, methodOn_TestClick, true); // note the change here

eventClick.AddEventHandler(obj, handler);

TestClick, EventArgs.

.

public void TestClick(object sender, EventArgs e)
{
    PropertyInfo prop_ID = e.GetType().GetProperty("ID");

    int id = Convert.toInt32(prop_ID.GetValue(e, null));
}
+7
+1

Activator.CreateInstance(), ?

:

type.GetFields() , ( , heirachy, type.BaseType, , , ).

FieldInfo , GetValue() FieldInfo, . , . FieldInfo.SetValue(myObject, Delegate.Combine(currentValue, myHandler)).

I am sure that with Delegate.Combine you just need to make sure that the signature of your event handler matches, but not the actual type. Therefore, this should be enough to create your own delegate with the same signature.

-2
source

Source: https://habr.com/ru/post/1786112/


All Articles