Connect delegate to event using reflection?

I have 2 DLLs, 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 "Hello"; } } } 

I use InvokeMember to get the result from B.dll, and I also want B.dll to be Test() before returning the result. So, how can I bind delegate to event in B.dll through reflection?

Any help would be appreciated!

+4
source share
1 answer

Get the event using typeof(B).GetEvent("Test") , and then connect it using EventInfo.AddEventHandler . Code example:

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

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


All Articles