使用DynamicMethod的和动态的ILGenerator事件发生在C#
-
21-08-2019 - |
题
我需要生成基于在运行时EventInfo对象的事件处理程序,并调用该事件处理程序中的方法。类似如下:
public void RegisterAction(ActionData actionData, EventInfo eventInfo,
Control control)
{
MethodInfo methodInfo = eventInfo.EventHandlerType.GetMethod("Invoke");
List<Type> ps = new List<Type>();
foreach (ParameterInfo info in methodInfo.GetParameters())
{
ps.Add(info.ParameterType);
}
DynamicMethod method = new DynamicMethod("Adapter",
typeof (void),
ps.ToArray(),
GetType(),
true);
ILGenerator generator = method.GetILGenerator();
// Here I need to generate a method to do the following:
// ExecuteAction(actionData);
// Then I can use this runtime method as an event handler and
// bind it to the control
Delegate proxy = method.CreateDelegate(eventInfo.EventHandlerType, this);
eventInfo.AddEventHandler(control, proxy);
}
我需要在产生IL代码的注释部分帮助。
解决方案
public void RegisterAction(ActionData actionData, EventInfo eventInfo,
Control control)
{
MethodInfo methodInfo = eventInfo.EventHandlerType.GetMethod("Invoke");
List<Type> ps = new List<Type>();
ps.Add (typeof (ActionData)) ;
foreach (ParameterInfo info in methodInfo.GetParameters())
{
ps.Add(info.ParameterType);
}
DynamicMethod method = new DynamicMethod("Adapter",
typeof (void),
ps.ToArray(),
GetType(),
true);
// compatible signatures for ExecuteAction
// (assuming you aren't interested in sender and eventArgs):
// static void ExecuteAction (ActionData) ;
// void ActionData.ExecuteAction () ;
MethodInfo miExecuteAction = <...> ;
ILGenerator generator = method.GetILGenerator();
generator.Emit (OpCodes.Ldarg_0) ;
generator.Emit (OpCodes.Call, miExecuteAction) ;
generator.Emit (OpCodes.Ret) ;
// if you want to pass this to ExecuteAction,
// you'll need to put it into actionData.
Delegate proxy = method.CreateDelegate(eventInfo.EventHandlerType, actionData);
eventInfo.AddEventHandler(control, proxy);
}
修改:现在想想看,如果你所有的活动遵循(发件人,参数)模式,你甚至不需要做乱用SRE:
public static void Execute<T> (ActionData data, object sender, T args)
where T : EventArgs
{
ExecuteAction (data) ;
}
public void RegisterAction (ActionData actionData, EventInfo eventInfo,
Control control)
{
MethodInfo compatibleMethod = typeof (this).GetMethod ("Execute",
BindingFlags.Static | BindingFlags.Public).MakeGenericMethod (
eventInfo.EventHandlerType.GetMethod ("Invoke").GetParameters ()[1].ParameterType)) ;
eventInfo.AddEventHandler (control,
Delegate.CreateDelegate (eventInfo.EventHandlerType, actionData,
compatibleMethod)) ;
}
其他提示
我猜你想从您的活动的MethodInfo作出委托...
如果这样,这里是描述如何的制品去这个问题。所需的IL代码的文章中进行了说明。
不隶属于 StackOverflow