如何在运行时触发事件

8
我希望能够在运行时使用C#生成实现接口的类。我已经成功发出了方法和属性,但是我没有成功地发出事件。以下是我希望发出的代码:命名空间:TestInterfaces,类:TestIImplementMe。
public event EventHandler SimpleEvent;

以下是生成的IL代码:

.event [mscorlib]System.EventHandler SimpleEvent
{
    .addon instance void TestInterfaces.TestIImplementMe::add_SimpleEvent(class [mscorlib]System.EventHandler)
    .removeon instance void TestInterfaces.TestIImplementMe::remove_SimpleEvent(class [mscorlib]System.EventHandler)
}

.method public final hidebysig specialname newslot virtual 
    instance void add_SimpleEvent (
        class [mscorlib]System.EventHandler 'value'
    ) cil managed 
{
    // Method begins at RVA 0x330c
    // Code size 48 (0x30)
    .maxstack 3
    .locals init (
        [0] class [mscorlib]System.EventHandler,
        [1] class [mscorlib]System.EventHandler,
        [2] class [mscorlib]System.EventHandler,
        [3] bool
    )

    IL_0000: ldarg.0
    IL_0001: ldfld class [mscorlib]System.EventHandler TestInterfaces.TestIImplementMe::SimpleEvent
    IL_0006: stloc.0
    // loop start (head: IL_0007)
        IL_0007: ldloc.0
        IL_0008: stloc.1
        IL_0009: ldloc.1
        IL_000a: ldarg.1
        IL_000b: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate)
        IL_0010: castclass [mscorlib]System.EventHandler
        IL_0015: stloc.2
        IL_0016: ldarg.0
        IL_0017: ldflda class [mscorlib]System.EventHandler TestInterfaces.TestIImplementMe::SimpleEvent
        IL_001c: ldloc.2
        IL_001d: ldloc.1
        IL_001e: call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class [mscorlib]System.EventHandler>(!!0&, !!0, !!0)
        IL_0023: stloc.0
        IL_0024: ldloc.0
        IL_0025: ldloc.1
        IL_0026: ceq
        IL_0028: ldc.i4.0
        IL_0029: ceq
        IL_002b: stloc.3
        IL_002c: ldloc.3
        IL_002d: brtrue.s IL_0007
    // end loop
    IL_002f: ret
} // end of method TestIImplementMe::add_SimpleEvent

.method public final hidebysig specialname newslot virtual 
    instance void remove_SimpleEvent (
        class [mscorlib]System.EventHandler 'value'
    ) cil managed 
{
    // Method begins at RVA 0x3348
    // Code size 48 (0x30)
    .maxstack 3
    .locals init (
        [0] class [mscorlib]System.EventHandler,
        [1] class [mscorlib]System.EventHandler,
        [2] class [mscorlib]System.EventHandler,
        [3] bool
    )

    IL_0000: ldarg.0
    IL_0001: ldfld class [mscorlib]System.EventHandler TestInterfaces.TestIImplementMe::SimpleEvent
    IL_0006: stloc.0
    // loop start (head: IL_0007)
        IL_0007: ldloc.0
        IL_0008: stloc.1
        IL_0009: ldloc.1
        IL_000a: ldarg.1
        IL_000b: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate)
        IL_0010: castclass [mscorlib]System.EventHandler
        IL_0015: stloc.2
        IL_0016: ldarg.0
        IL_0017: ldflda class [mscorlib]System.EventHandler TestInterfaces.TestIImplementMe::SimpleEvent
        IL_001c: ldloc.2
        IL_001d: ldloc.1
        IL_001e: call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class [mscorlib]System.EventHandler>(!!0&, !!0, !!0)
        IL_0023: stloc.0
        IL_0024: ldloc.0
        IL_0025: ldloc.1
        IL_0026: ceq
        IL_0028: ldc.i4.0
        IL_0029: ceq
        IL_002b: stloc.3
        IL_002c: ldloc.3
        IL_002d: brtrue.s IL_0007
    // end loop
    IL_002f: ret
} // end of method TestIImplementMe::remove_SimpleEvent

我已经完成了除这行之外的所有内容: IL_001e: call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange(!!0&, !!0, !!0)

这里的意思是什么:!!0, !!0&?

如何使用IL emit调用此方法?

我尝试调用该方法,但当我添加处理程序时:

obj.SimpleEvent += new EventHandler(obj_SimpleEvent);

我遇到了这个异常:

System.BadImageFormatException was unhandled
  Message=An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
  Source=DataBuilderAssembly
  StackTrace:
       at NewTest.add_SimpleEvent(EventHandler value)
       at TestInterfaces.Program.Main(String[] args) in D:\Dev\Private\TestInterfaces\TestInterfaces\Program.cs:line 47
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

以下是发射事件添加方法的代码所在位置:
methodName = "add_SimpleEvent";
actionHanler = typeof(Delegate).GetMethod("Combine", new Type[]{typeof(Delegate),typeof(Delegate)});
eventField = typeBuilder.DefineField(info.Name, info.EventHandlerType, FieldAttributes.Private);
compareExchange = GetGenericMethod(typeof(Interlocked), "CompareExchange");// finds the correct method to call.
// thanks to @marc, create the specific method with the correct type
compareExchange = compareExchange.MakeGenericMethod(info.EventHandlerType);

生成事件方法

private static MethodBuilder GenerateEventMethod(string methodName, MethodInfo actionHanler, TypeBuilder typeBuilder, EventInfo info, FieldBuilder eventField, MethodInfo compareExchange)
{
    MethodBuilder method = typeBuilder.DefineMethod(methodName, InternalMethodsAttributes, null, new Type[] { info.EventHandlerType });
    method.DefineParameter(0, ParameterAttributes.Retval, null);
    method.DefineParameter(1, ParameterAttributes.In, "value");
    ILGenerator il = method.GetILGenerator();
    il.DeclareLocal(info.EventHandlerType);
    il.DeclareLocal(info.EventHandlerType);
    il.DeclareLocal(info.EventHandlerType);
    il.DeclareLocal(typeof (bool));

    Label loop = il.DefineLabel();

    il.Emit(OpCodes.Ldarg_0);
    il.Emit(OpCodes.Ldfld, eventField);
    il.Emit(OpCodes.Stloc_0);

    il.MarkLabel(loop);// loop start (head: IL_0007)

    il.Emit(OpCodes.Ldloc_0);
    il.Emit(OpCodes.Stloc_1);
    il.Emit(OpCodes.Ldloc_1);
    il.Emit(OpCodes.Ldarg_1);

    il.Emit(OpCodes.Call, actionHanler);
    il.Emit(OpCodes.Castclass, info.EventHandlerType);

    il.Emit(OpCodes.Stloc_2);
    il.Emit(OpCodes.Ldarg_0);

    il.Emit(OpCodes.Ldflda, eventField);

    il.Emit(OpCodes.Ldloc_2);
    il.Emit(OpCodes.Ldloc_1);

    // How to do this?
    //IL_001e: call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class [mscorlib]System.EventHandler`1<class [mscorlib]System.ConsoleCancelEventArgs>>(!!0&, !!0, !!0)
    //il.Emit(OpCodes.Call, !!0 compareExchange(!!0&,!!0, !!0));
    il.Emit(OpCodes.Call, compareExchange);

    il.Emit(OpCodes.Stloc_0);
    il.Emit(OpCodes.Ldloc_0);
    il.Emit(OpCodes.Ldloc_1);
    il.Emit(OpCodes.Ceq);
    il.Emit(OpCodes.Ldc_I4_0);
    il.Emit(OpCodes.Ceq);
    il.Emit(OpCodes.Stloc_3);
    il.Emit(OpCodes.Ldloc_3);
    il.Emit(OpCodes.Brtrue_S, loop);
    // end loop
    il.Emit(OpCodes.Ret);

    return method;
}

GetGenericMethod(针对此问题特定的方法):

private static MethodInfo GetGenericMethod(Type type, string methodName)
{
    var q = from m in type.GetMethods()
            where m.Name == methodName && m.IsGenericMethod
            select m;
    return q.FirstOrDefault();
}

感谢您,Ofir。
2个回答

5
< p > !!0 CompareExchange<T> 中的 T(即!!0 是第一个(从零开始)泛型类型参数),!!0&ref T - 但这些只是指定重载。重要的是在其前面几行中的 ldflda(按引用加载字段)、ldloc.2 和 ldloc.1,以及它返回一个 T


谢谢您的快速回复。我已经正确加载了这些字段,但它仍然无法正常工作,就像我之前所解释的一样。有什么想法吗? - Ofir
@Ofir 在你开始着手之前,你确定这里需要线程安全吗?实际上大多数实现并不需要。你可以尝试使用ldfld、ldarg.0、call Delegate.Combine和stfld来代替。 - Marc Gravell
@Ofir,你能展示一下你目前正在使用的代码吗?这可能只是正确指定通用方法的问题。 - Marc Gravell
@Ofir,你能展示一下GetGenericMethod吗?它是否执行必要的MakeGenericMethod操作? - Marc Gravell
1
@Ofir 是的,这很清楚:只需将 compareExchange(通过“调用”)更改为:compareExchange.MakeGenericMethod(info.EventHandlerType) - 您正在请求 开放式泛型 方法。 - Marc Gravell
嗨@马克,正中要害。 - Ofir

1
我建议用C#编写代码,编译后使用你最喜欢的.NET反编译器来检查确切的IL代码。这样做后,生成相同的动态代码应该很容易。

谢谢,这就是我获取IL作为参考的方法。 - Ofir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接