AddEventHandler using reflection
.net, c#, events, reflection
Solution
Here's a sample showing how to attach an event using reflection:
class Program
{
static void Main(string[] args)
{
var p = new Program();
var eventInfo = p.GetType().GetEvent("TestEvent");
var methodInfo = p.GetType().GetMethod("TestMethod");
Delegate handler =
Delegate.CreateDelegate(eventInfo.EventHandlerType,
p,
methodInfo);
eventInfo.AddEventHandler(p, handler);
p.Test();
}
public event Func<string> TestEvent;
public string TestMethod()
{
return "Hello World";
}
public void Test()
{
if (TestEvent != null)
{
Console.WriteLine(TestEvent());
}
}
}
Problem
I have this piece of code that does not work: ``` public CartaoCidadao() { InitializeComponent(); object o = WebDAV.Classes.SCWatcher.LoadAssembly(); MethodInfo method = this.GetType().GetMethod("Inserted", BindingFlags.NonPublic | BindingFlags.Instance); EventInfo eventInfo = o.GetType().GetEvent("CardInserted"); Type type = eventInfo.EventHandlerType; Delegate handler = Delegate.CreateDelegate(type, this , method); eventInfo.AddEventHandler(o, handler); } void Inserted(string readerName, string cardName) { System.Windows.Forms.MessageBox.Show(readerName); } ``` The Event CardInserted exists in another DLL file and object "o" loads OK. The delegate handler has a value after effect. I only can't fire the event.