I am trying to subscribe to an event using reflection. The guarantee is
that the the event delegate will be of type EventHandler or at least the e
parameter inherits from EventArgs. Hard coding this is possible, for
example in the example below I am subscribing TestMethod to Event and the
EventArgs parameter differs. But I need to do this same thing through
reflection using an anonymous method. It seems like it should be possible,
but I can't find a way. Is this possible?
I think the core problem is that this doesn't compile:
EventHandler<EventArgs2testDelegate2 = delegate(Object sender,
EventArgs blah) { };
However, it compiles fine when not using an anonymous method.
using System;
using System.Reflection;
class EventArgs2 : EventArgs { }
class Program
{
public static event EventHandler<EventArgs2Event;
public static void TestMethod(Object sender, EventArgs blah)
{
return;
}
public static void Main(
String[] args)
{
EventInfo eventInfo = typeof(Program).GetEvent("Event");
// Compiles fine even though the TestMethod parameters do
// not match /exactly/, though they do match logically.
EventHandler<EventArgs2testDelegate1 = new
EventHandler<EventArgs2>(TestMethod);
// These work fine
eventInfo.AddEventHandler(null, testDelegate2);
Event += testDelegate2;
// Try doing this with an anonymous method.
EventHandler testDelegate2 = delegate(Object sender, EventArgs blah)
{
return;
};
// Throws an exception because the delegate types don't match.
eventInfo.AddEventHandler(null, testDelegate2);
// Does not compile because the delegate parameters do
// not match /exactly/, though they do match logically.
Event += testDelegate2;
return;
}
}