简体   繁体   中英

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? 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? Here I've created a new void method Foo() and created it as a member of the EmitTest class. The runtime says Foo() is not found on EmitTest

You're misunderstanding the owner parameter.
MSDN says : (emphasis added)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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