我正在尝试将一个委托附加到另一个委托的调用列表。通过这种方式,我实现了对现有事件的一种Hook。我需要在每个被调用的事件之后运行一些东西。
下面的示例工作,只要类型暴露的委托和i传递的Action具有完全相同的签名。(On1和OnAll事件都是用Action委托声明的,所以它可以工作)。
代码:如何将Action与由事件修饰符公开的现有委托挂钩。
public static class ReflectionExtensions
{
public static IEnumerable<EventInfo> GetEvents(this object obj)
{
var events = obj.GetType().GetEvents();
return events;
}
public static void AddHandler(this object obj, Action action)
{
var events = obj.GetEvents();
foreach (var @event in events)
{
@event.AddEventHandler(obj, action);
}
}
}
示例:
public class Tester
{
public event Action On1;
public event Action On2;
public void RaiseOn1()
{
On1();
}
public void RaiseOn2()
{
On2();
}
}
class Program
{
static void Main(string[] args)
{
var t = new Tester();
t.On1 += On1;
t.On2 += On2;
t.AddHandler(OnAll);
t.RaiseOn1();
t.RaiseOn2();
}
public void On1() { }
public void On2() { }
public void OnAll() { }
}
问题:当在Tester中使用事件修饰符暴露的委托没有相同的签名时,我得到了一个很想要的和明显的异常,该异常状态(用我的话来说), Action
不能添加到Action<int>
的调用列表中。是有意义的。
为了说清楚,我描述的是以下内容:
public event Action<int> On1;
public void On1(int i){}
我正在寻找的是一种方法来创建与EventHandlerType相同类型的另一个Delegate。为了做到这一点,我需要创建一个带有EventHandlerType签名i的方法,该方法将在内部调用动作。
类似于:
public static void AddHandler(this object obj, Action action)
{
var events = obj.GetEvents();
foreach (var @event in events)
{
// method with the signeture of EventHandlerType which does action();
MethodInfo wrapperMethod = WrapAction(@event.EventHandlerType, action);
Delegate handler = Delegate.CreateDelegate(@event.EventHandlerType, action.Target, wrapperMethod);
@event.AddEventHandler(obj, handler);
}
}
这似乎有效…里面有各种评论…我不确定这是不是最好的方法。我正在构建一个Expression
树来执行委托调用。
public static void AddHandler(this object obj, Action action)
{
var events = obj.GetEvents();
foreach (var @event in events)
{
// Simple case
if (@event.EventHandlerType == typeof(Action))
{
@event.AddEventHandler(obj, action);
}
else
{
// From here: http://stackoverflow.com/a/429564/613130
// We retrieve the parameter types of the event handler
var parameters = @event.EventHandlerType.GetMethod("Invoke").GetParameters();
// We convert it to ParameterExpression[]
ParameterExpression[] parameters2 = Array.ConvertAll(parameters, x => Expression.Parameter(x.ParameterType));
MethodCallExpression call;
// Note that we are "opening" the delegate and using
// directly the Target and the Method! Inside the
// LambdaExpression we will build there won't be a
// delegate call, there will be a method call!
if (action.Target == null)
{
// static case
call = Expression.Call(action.Method);
}
else
{
// instance type
call = Expression.Call(Expression.Constant(action.Target), action.Method);
}
// If you are OK to create a delegate that calls another
// delegate, you can:
// call = Expression.Call(Expression.Constant(action), typeof(Action).GetMethod("Invoke"));
// instead of the big if/else
var lambda = Expression.Lambda(@event.EventHandlerType, call, parameters2);
@event.AddEventHandler(obj, lambda.Compile());
}
}
}