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"


- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01