任务是在运行时创建事件处理程序。对于不同的事件,我需要使用不同的参数值调用一种方法。事件及其编号仅在运行时已知。所以我试图生成动态方法,每个方法都将分配给某个事件,但通常它们都只是将一些值传递给实例方法并调用它。
如果可以以更简单的方式完成类似的事情,那就太好了。我的意思是在订阅阶段传递一些值,然后在触发事件时获取它。
这就是我现在想要做的:
public class EventSource
{
public event EventHandler eventOne;
public event EventHandler eventTwO;
public event EventHandler eventThree;
}
public class EventListener
{
SubscribeForEvents()
{
BindingFlags flags =
BindingFlags.IgnoreCase |
BindingFlags.Public |
BindingFlags.Instance;
// Suppose we've already got EventInfo
// and target source somewhere
// so we can do eventInfo.AddEventHandler(target, delegate)
// Now we need a delegate.
int value = 42;
Type tDelegate = eventInfo.EventHandlerType;
// http://msdn.microsoft.com/en-us/library/ms228976(VS.95).aspx
Type returnType = GetDelegateReturnType(tDelegate);
DynamicMethod listener = new DynamicMethod("", null,
GetDelegateParameterTypes(tDelegate), this.GetType());
/////////
Type[] callParameters = { typeof(int) };
MethodInfo method = this.GetType().GetMethod("ToCallFromDelegate", flags);
ILGenerator generator = listener.GetILGenerator();
// No success in this mess. What's wrong?
generator.Emit(OpCodes.Ldc_I4, value);
generator.Emit(OpCodes.Call, method);
generator.Emit(OpCodes.Pop);
generator.Emit(OpCodes.Ret);
/////////////
Delegate delegate = listener.CreateDelegate(tDelegate);
eventInfo.AddEventHandler(target, delegate);
// When triggered, there is InvalidProgramException
}
void ToCallFromDelegate(int value)
{
doSomething();
}
}