参考“这个” 在动态事件处理程序中
在我的“myClass”类中,我使用 Reflection.Emit 为 myClass 类成员之一动态编写事件处理程序。
我已经成功地做到了这一点。
现在,我想修改事件处理程序以调用 myClass 类中的实例方法之一。
但是,我无法弄清楚如何使用 Reflection.Emit 将对“this”的引用推送到 MSIL 堆栈上。 在事件处理程序中,Ldarg_0 不是对“this”的引用,而是事件处理程序的第一个参数。
有谁知道如何将对“this”的引用推送到堆栈上,以便我可以调用实例方法。 例如,我希望 C# 代码如下所示:
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
}
}
谢谢!
In my 'myClass' class, I am using Reflection.Emit to dynamically write an event handler for one of the myClass class' members.
I have done this successfully.
Now, I want to modify the event handler to call one of the instance methods in the myClass class.
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.
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
}
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您使用
Reflection.Emit
(我假设这里使用DynamicMethod
)时,您可以选择生成代码的第一个参数是,并且它可以由委托隐式传递,如下所示:When you use
Reflection.Emit
(and I'm presumingDynamicMethod
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:如果您在 main 中,则没有 Main 类的实例。 主要功能是静态的。
If you are in main, then there is no instance of your Main class. The main function is static.