简体   繁体   English

我可以使用System.Reflection.Emit将动态方法添加到现有类型吗?

[英]Can I add a dynamic method to an existing type using System.Reflection.Emit?

I just started learning the Emit namespace - is the following valid? 我刚开始学习Emit命名空间 - 以下是否有效? This throws an exception: 这引发了一个异常:

public class EmitTest
{
    public void Test()
    {
        DynamicMethod dynMeth = new DynamicMethod("Foo", null, null, typeof(EmitTest));
        ILGenerator gen = dynMeth.GetILGenerator();
        gen.EmitWriteLine("Foo");
        gen.Emit(OpCodes.Ret);
        dynMeth.Invoke(null, null);
        dynamic d = this;
        d.Foo();
    }
}

Is there anyway to make this work as intended or is it a limitation of DLR? 反正有没有按照预期进行这项工作,还是DLR的限制? Here I've created a new void method Foo() and created it as a member of the EmitTest class. 在这里,我创建了一个新的void方法Foo(),并将其创建为EmitTest类的成员。 The runtime says Foo() is not found on EmitTest 运行时说EmitTest上找不到Foo()

You're misunderstanding the owner parameter. 你误解了owner参数。
MSDN says : (emphasis added) MSDN :(重点补充)

owner

A Type with which the dynamic method is logically associated. 与动态方法逻辑关联的类型。 The dynamic method has access to all members of the type. 动态方法可以访问该类型的所有成员。

You cannot add methods to an existing type. 您无法将方法添加到现有类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM