The MS documentation already covers this:
How to: Hook Up a Delegate Using Reflection | Microsoft Docs[
^]
Assembly assembly = Assembly.LoadFrom("RefTest.dll");
Type typeClass = assembly.GetType("RefTest.Test");
object obj = Activator.CreateInstance(typeClass);
EventInfo messageEvent = typeClass.GetEvent("OnMessage");
MethodInfo receiveMethod = typeof(Program).GetMethod("Receive", BindingFlags.Public | BindingFlags.Static);
Delegate handler = Delegate.CreateDelegate(messageEvent.EventHandlerType, null, receiveMethod);
messageEvent.GetAddMethod().Invoke(obj, new[] { handler });
MethodInfo writeStringMethod = typeClass.GetMethod("WriteString");
writeStringMethod.Invoke(obj, null);
NB: You'll need to update your
Receive
method to match the expected signature of the event - eg:
public static void Receive(string message) ...
You should also follow the
naming[
^] and
design[
^] guidelines for events as far as possible:
public class Test
{
public event EventHandler<string> Message;
public void WriteString()
{
Console.WriteLine("Write String");
Message?.Invoke(this, "ActionMessage");
}
}
public static void Receive(object sender, string message) { ... }
In an ideal world, the second argument to the event would be a class derived from
System.EventArgs
. But unless you can find a built-in one that suits your requirements, it could be tricky to create a custom class which is shared between the
RefTest
assembly and the calling assembly.