参考“这个”动态事件处理程序 [英] Reference 'this' in dynamic event handler

查看:123
本文介绍了参考“这个”动态事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的'MyClass的'课,我使用Reflection.Emit的动态写MyClass类成员之一的事件处理程序。

In my 'myClass' class, I am using Reflection.Emit to dynamically write an event handler for one of the myClass class' members.

我已经这样做了成功。

现在,我要修改的事件处理程序调用在myClass类的实例方法之一。

Now, I want to modify the event handler to call one of the instance methods in the myClass class.

不过,我无法弄清楚如何引用推到'这'上使用的Reflection.Emit的MSIL堆栈。在事件处理程序,Ldarg_0不是'这'的引用,而是事件处理程序的第一个参数。

However, I cannot figure out how to push a reference to 'this' onto the MSIL stack using Reflection.Emit. Within the event handler, Ldarg_0 is not a reference to 'this', but rather the first parameter of the event handler.

有谁知道如何引用推到'这'在堆栈上,这样我可以调用一个实例方法。例如,这就是我想要的C#代码如下:

Does anyone know how to push a reference to 'this' on the stack so that I can call an instance method. For example, this is what I would want the c# code to look like:

public class myClass
{
private myObj1 obj1;
public myClass() {
   this.init();
}

private void init()
{
   obj1.myEvent += new myEvent_EventHandler(theHandler);
}

private void theHandler(myObj2 obj2, myObj3 obj3)
{
   // this is the part I'm having trouble with
   this.myFunction(obj2);
}

private void myFunction(myObj2 obj2)
{
   // irrelevant
}
}

谢谢!

推荐答案

在使用 Reflection.Emit的(我假设 DynamicMethod的在这里),去选择的第一个参数生成的代码是什么,它​​可以隐含地委托传递,就像这样:

When you use Reflection.Emit (and I'm presuming DynamicMethod here), you get to choose what the first argument to the generated code will be, and it can be passed implicitly by the delegate, like this:

using System;
using System.Reflection.Emit;

public class App
{
    static void Main()
    {
        DynamicMethod m = new DynamicMethod("test", typeof(void),
            new[] { typeof(App), // <-- type of first argument, your choice
                typeof(string) });

        var cg = m.GetILGenerator();

        cg.Emit(OpCodes.Ldarg_0);
        cg.Emit(OpCodes.Ldarg_1);
        cg.EmitCall(OpCodes.Call,
            typeof(App).GetMethod("ShowString"), null);

        cg.Emit(OpCodes.Ret);

        Action<string> d = (Action<string>) 
            m.CreateDelegate(typeof(Action<string>), 
            new App()); // <-- this is the first argument, *your* choice

        MyEvent += d;

        // Trigger event
        MyEvent("Hello there");
    }

    static event Action<string> MyEvent;

    public void ShowString(string s)
    {
        Console.WriteLine(s);
    }
}

这篇关于参考“这个”动态事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆