Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用反射将委托连接到事件?_C#_Events_Reflection_Delegates_Invoke - Fatal编程技术网

C# 使用反射将委托连接到事件?

C# 使用反射将委托连接到事件?,c#,events,reflection,delegates,invoke,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");

我有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()
。那么,如何通过反射将
委托
连接到B.dll中的
事件


任何帮助都将不胜感激

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

非常感谢你的快速回答