Reference #39;this#39; in dynamic event handler(在动态事件处理程序中引用“this)
问题描述
在我的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 将对this"的引用推送到 MSIL 堆栈.在事件处理程序中,Ldarg_0 不是对this"的引用,而是事件处理程序的第一个参数.
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.
有谁知道如何在堆栈上推送对this"的引用,以便我可以调用实例方法.例如,这就是我希望 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);
}
}
这篇关于在动态事件处理程序中引用“this"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在动态事件处理程序中引用“this"
基础教程推荐
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01