在Silverlight中使用DynamicMethod时,会出现VerificationException

问题描述

|| 我想通过委托调用某些方法,但正在获取VerificationException。我正在使用以下代码
    internal delegate void Delegete_add_Startup(object o,StartupEventHandler s);
    Delegete_add_Startup del;

    public App()
    {
        //this.Startup += this.Application_Startup;

        Type[] parameterTypes = new Type[2];
        parameterTypes[0] = typeof(object);
        parameterTypes[1] = typeof(StartupEventHandler);

        MethodInfo mi = typeof(Application).getmethod(\"add_Startup\",BindingFlags.Public | BindingFlags.Instance);

        Dynamicmethod method = new Dynamicmethod(string.Empty,mi.ReturnType,parameterTypes);
        method.InitLocals = true;
        ILGenerator iLGenerator = method.GetILGenerator();
        iLGenerator.Emit(OpCodes.Ldarg_0);
        iLGenerator.Emit(OpCodes.Ldarg_1);
        iLGenerator.Emit(OpCodes.Call,mi);
        iLGenerator.Emit(OpCodes.Ret);
        del = (Delegete_add_Startup)method.CreateDelegate(typeof(Delegete_add_Startup));


        del(this,new StartupEventHandler(Application_Startup));


        this.Exit += this.Application_Exit;
        this.UnhandledException += this.Application_UnhandledException;

        InitializeComponent();
    }
基本上,我想打电话给 this.Startup + = this.Application_Startup; 通过使用上面的代码的委托。 这给出了VerificationException:操作可能会破坏运行时异常。 通过将此代码放入全新的Silverlight App项目的App构造函数中,可以非常轻松地重现该代码。 我究竟做错了什么?     

解决方法

对于您的情况,您可以将OpCodes.Call替换为OpCodes.CallVirt,它应该会更好地工作(没经过理解,我是Silverlight CLR精妙的菜鸟)。