开发者

Hook up a Delegate to an Event using reflection?

I have 2 DLL, A.dll contains:

namespace Alphabet
{
    public delegate void TestHandler();

    public class A  
    {
        private void DoTest()
        {
            Type type = Assembly.LoadFile("B.dll").GetType("Alphabet.B");                       

            Object o = Activator.CreateInstance(type);

            string ret = type.InvokeMember("Hello", BindingFlags.InvokeMethod | BindingFlags.Default, null, o, null);
        }
    }
}

and B.dll contains

namespace Alphabet
{   
    public class B
    {
        public event TestHandler Test();

        public string Hello()
        {
            if (null != Test) Test();
            return "开发者_如何学GoHello";
        }
    }
}

I'm using InvokeMember to get the result from B.dll and I also want B.dll to Test() before return the result. So, how can I hook up the delegate to the event in B.dll through reflection?

Any helps would be appreciated!


Get the event with typeof(B).GetEvent("Test") and then hook it up with EventInfo.AddEventHandler. Sample code:

using System;
using System.Reflection;

public delegate void TestHandler();

public class A  
{
    static void Main()
    {
        // This test does everything in the same assembly just
        // for simplicity
        Type type = typeof(B);
        Object o = Activator.CreateInstance(type);

        TestHandler handler = Foo;
        type.GetEvent("Test").AddEventHandler(o, handler);
        type.InvokeMember("Hello",
                          BindingFlags.Instance | 
                          BindingFlags.Public |
                          BindingFlags.InvokeMethod,
                          null, o, null);
    }

    private static void Foo()
    {
        Console.WriteLine("In Foo!");
    }
}

public class B
{
    public event TestHandler Test;

    public string Hello()
    {
        TestHandler handler = Test;
        if (handler != null)
        {
            handler();
        }
        return "Hello";
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜