Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

.net - Subscribe to an event with Reflection

I have a very simple class :

class Trace
{
    void WriteTrace()
    {
        Console.WriteLine("Trace !");
    }
}

I want this class subscribes to an event, for example the load event of a form control. The control and event are define dynamically so I want to use reflection to do this I'm trying something like that :

In my class Trace I have this method :

public void SubscribeEvent (Control control)
{
        if (type.IsAssignableFrom(control.GetType()))
        {
            Trace test = this;
            MethodInfo method = typeof(Trace).GetMethod("WriteTrace");

            // Subscribe to the event
            EventInfo eventInfo = control.GetType().GetEvent("Load"); // We suppose control is a form 
            Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, control, method); // ERROR : Error binding to target method

        }
    }
}

There is an error on the last line : Error binding to target method. What's wrong in my snippet ?

Thank you !

EDIT : Ok, there is no more error but when the event "Load" is raised from the Form, the method WriteTrace is not called (I have put a breakpoint but there is not reached). Why ?

Sorry for the edit, it works very fine :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With a few changes, I was able to execute your sample.

Firstly, the method on Trace must have a different signature to correspond with the EventHandler type:

public class Trace
{
    public void WriteTrace(object sender, EventArgs e)
    {
        Console.WriteLine("Trace !");
    }
}

Next, a few changes were made to the SubscribeEvent:

public void SubscribeEvent(Control control)
{
    if (typeof(Control).IsAssignableFrom(control.GetType()))
    {
        Trace test = this;
        MethodInfo method = typeof(Trace).GetMethod("WriteTrace");

        EventInfo eventInfo = control.GetType().GetEvent("Load");

        // Create the delegate on the test class because that's where the
        // method is. This corresponds with `new EventHandler(test.WriteTrace)`.
        Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, test, method);
        // Assign the eventhandler. This corresponds with `control.Load += ...`.
        eventInfo.AddEventHandler(control, handler);
    }
}

I hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...