使用反射将代表连接到事件?

时间:2011-03-19 08:42:51

标签: c# events reflection delegates invoke

我有2个DLL,A.dll包含:

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);
        }
    }
}

和B.dll包含

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

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

我正在使用InvokeMember从B.dll获取结果,我还希望在返回结果之前将B.dll发送到Test()。那么,如何通过反射将delegate连接到B.dll中的event

任何帮助都将不胜感激!

1 个答案:

答案 0 :(得分:7)

使用typeof(B).GetEvent("Test")获取活动,然后将其与EventInfo.AddEventHandler联系起来。示例代码:

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";
    }
}