I have a bunch of generic events I want to subscribe to and make them all call one non-generic method. Here's my code:
public delegate void PropertyChangedDelegate<OwnerType, PropertyType>(OwnerType sender, PropertyType oldValue, PropertyType newValue);
public class EventObject
{
public event PropertyChangedDelegate<Object, Boolean> PropertyChanged;
public event PropertyChangedDelegate<Object, Int32> XChanged;
}
static void Main()
{
EventObject eventObject = new EventObject();
EventInfo eventInfo = eventObject.GetType().GetEvent("PropertyChanged");
eventInfo.AddEventHandler(eventObject, PropertyChanged);
}
static void PropertyChanged(Object obj, Object oldValue, Object newValue)
{
}
Obviously this doesn't work, is there any way to do a wrapper generic method?
You can't pass a method group as such in place of a delegate. You can specify the exact delegate your method matches to, like this:
But it still would give you runtime exception since the signatures don't match.
Why not the straightforward
+=
implementation?But this wont compile because of type mismatch in signature. You have to either change signature of delegate
or change signature of event
(but that spoils all your efforts to have a strongly typed delegate) or change signature of method
which is what I would go with.
The issue is that
PropertyChanged
method is not contravariant to thePropertyChangedDelegate
type because sendingbool
asobject
require boxing, so it is clear that you cannot make delegate to work universally with all events. The solution is to write a static method as a "landing method". Here is my solution:Inspired from
Using Reflection to get static method with its parameters
and
Create generic delegate using reflection