我从这里复制了代码:https ://whathecode.wordpress.com/2012/03/26/null-checks-for-event-handlers-an-aspect-solution/
但是当事件在通用类型的类中时,我似乎无法让它工作。我有一个类定义为:
Public Class MultiKeyDictionary<TFirstKey, TSecondKey, TValue>
以及以下事件:
public delegate void EventDelegate(TValue value);
public delegate void ReplacedEventDelegate(TValue oldValue, TValue newValue);
public event EventDelegate Added;
public event EventDelegate Removed;
public event ReplacedEventDelegate Replaced;
但是初始化代码异常抱怨类型的 ContainsGenericParameters 设置为 true (或类似的东西)。
我已将 RuntimeInitialize 方法中该链接中的代码更改为:
public override void RuntimeInitialize(EventInfo eventInfo) {
base.RuntimeInitialize(eventInfo);
Type eventType;
MethodInfo delegateInfo = eventInfo.EventHandlerType.MethodInfoFromDelegateType();
ParameterExpression[] parameters = delegateInfo.GetParameters().Select(p => Expression.Parameter(p.ParameterType)).ToArray();
if(eventInfo.EventHandlerType.ContainsGenericParameters) {
var genericDelegate = eventInfo.EventHandlerType.GetGenericTypeDefinition();
var genericParams = genericDelegate.GetGenericArguments();
eventType = genericDelegate.MakeGenericType(genericParams);
} else {
eventType = eventInfo.EventHandlerType;
}
Delegate emptyDelegate = Expression.Lambda(eventType, Expression.Empty(), "EmptyDelegate", true, parameters).Compile();
this.addEmptyEventHandler = instance => eventInfo.AddEventHandler(instance, emptyDelegate);
}
但我现在得到的只是一个 ArgumentException:“TValue”类型的 ParameterExpression 不能用于创建 emptyDelegate 行上的“TValue”类型的委托参数。