by Geert
29. December 2011 15:50
Recently I was working on true weak actions and wanted to do something like this:
1: public class WeakAction<TParameter>
2: {
3: public delegate void OpenInstanceGenericAction<TTarget>(TTarget @this, TParameter parameter);
4:
5: public WeakAction(object target, Action<TParameter> action)
6: {
7: var targetType = (target != null) ? target.GetType() : typeof(object);
8: var delegateType = typeof(OpenInstanceGenericAction<>).MakeGenericType(targetType, typeof(TParameter));
9:
10: _action = Delegate.CreateDelegate(delegateType, null, action.Method);
11: }
12: }
I was pretty sure I was doing it all right. In this code, I create a generic open instance handler to make sure I can invoke the method without referencing the instance itself. This allows me to write true weak actions.
Anyway, the error that pops up is:
System.ArgumentException: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.
Scratching my head over and over again, for about 1 hour, something came into my mind that couldn’t be true: would it be that I have to define the TParameter first, and then the TTarget, even when the delegate uses them in another order?
The answer seemed to be yes!
Apparently, you need to specify the order of arguments. So, because the delegate is part of a class defining the first generic argument (TParameter), you need to specify that first. So, it is not the order in which they are used inside the delegate, but the order of definition.