开发者

VerificationException when using DynamicMethod in Silverlight

开发者 https://www.devze.com 2023-02-24 22:42 出处:网络
I want to call certain methods via delegates but am getting VerificationException. I am using following code:

I want to call certain methods via delegates but am getting VerificationException. I am using following code:

    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(StartupEventHand开发者_高级运维ler);

        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();
    }

Basically, I am trying to call

this.Startup += this.Application_Startup;

via a delegate using the code above.

This gives a VerificationException: Operation could destabilize the runtime exception.

This is very easy to reproduce by putting this code in the App constructor of a brand new Silverlight App project. What am I doing wrong?


For your case, you may replace OpCodes.Call by OpCodes.CallVirt, it should work better (untested and ununderstood, I'm a rookie at Silverlight CLR subtleties).

0

精彩评论

暂无评论...
验证码 换一张
取 消