假设
methodName
是一种静态的
QueryWindow
,这应该起作用:
private static void RegisterEvent(object targetObject, string eventName, string methodName)
{
var eventInfo = targetObject.GetType().GetEvent(eventName);
var method = eventInfo.EventHandlerType.GetMethod("Invoke");
var types = method.GetParameters().Select(param => param.ParameterType);
var methodInfo = typeof(QueryWindow).GetMethod(methodName, new[] { typeof(object) });
// replaced typeof(void) by null
var dynamicMethod = new DynamicMethod(eventInfo.EventHandlerType.Name, null, types.ToArray(), typeof(QueryWindow));
ILGenerator ilGenerator = dynamicMethod.GetILGenerator(256);
// Using Ldarg_0 to pass the sender to methodName ; Ldarg_1 to pass the event args
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.EmitCall(OpCodes.Call, methodInfo, null);
// Added return
ilGenerator.Emit(OpCodes.Ret);
// Removed parameter definition (implicit from DynamicMethod constructor)
// Removed the target argument
var methodDelegate = dynamicMethod.CreateDelegate(eventInfo.EventHandlerType);
eventInfo.AddEventHandler(targetObject, methodDelegate);
}
既然可以使用.NET3.5,就应该创建一个表达式树。下面是另一个解决方案:
public class QueryWindow
{
public void RegisterEvent(object targetObject, string eventName, string methodName)
{
var eventInfo = targetObject.GetType().GetEvent(eventName);
var sender = Expression.Parameter(typeof (object), "sender");
var e = Expression.Parameter(typeof (EventArgs), "e");
var body = Expression.Call(Expression.Constant(this), methodName, null, e);
var lambda = Expression.Lambda(eventInfo.EventHandlerType, body, sender, e);
eventInfo.AddEventHandler(targetObject, lambda.Compile() );
}
public void OnEvent(object o)
{
Console.WriteLine(o);
}
}
请注意
OnEvent
方法不再是静态的。我还假设您尝试订阅的事件是遵循.NET约定的事件(发送方+事件参数)。这样,我们就可以利用逆差并始终传递一个lambda类型:
(object sender, EventArgs e) => { /* */ }