Create DynamicMethod to assign value to a property

2020-02-28 20:10发布

问题:

This is a learning exercise. I created a method that takes a Foo and a string and sets the A property. I used the Reflector disassembly to make the following emit code. The disassembly looks like this:

.method private hidebysig static void Spork(class ConsoleTesting.Foo f, string 'value') cil managed
{
    .maxstack 8
    L_0000: ldarg.0 
    L_0001: ldarg.1 
    L_0002: callvirt instance void ConsoleTesting.Foo::set_A(string)
    L_0007: ret 
}

Ok, so I modeled my emit code after that:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;


namespace ConsoleTesting
{
    class Foo
    {
        public string A { get; set; }
    }

    class Program
    {
        static Action<Foo, string> GenMethodAssignment(string propName)
        {
            MethodInfo setMethod = typeof(Foo).GetMethod("get_" + propName);
            if (setMethod == null)
                throw new InvalidOperationException("no property setter available");

            Type[] argTypes = new Type[] { typeof(Foo), typeof(String) };
            DynamicMethod method = new DynamicMethod("__dynamicMethod_Set_" + propName, null, argTypes, typeof(Program));
            ILGenerator IL = method.GetILGenerator();
            IL.Emit(OpCodes.Ldarg_0);
            IL.Emit(OpCodes.Ldarg_1);
            IL.Emit(OpCodes.Callvirt, setMethod);
            IL.Emit(OpCodes.Ret);
            method.DefineParameter(1, ParameterAttributes.In, "instance");
            method.DefineParameter(2, ParameterAttributes.In, "value");

            Action<Foo, string> retval = (Action<Foo, string>)method.CreateDelegate(typeof(Action<Foo, string>));
            return retval;
        }

        static void Main(string[] args)
        {
            Foo f = new Foo();
            var meth = GenMethodAssignment("A");
            meth(f, "jason");
            Console.ReadLine();
        }
    }

I'm getting this exception:

JIT Compiler encountered an internal limitation.

What the krunk does that mean, and how do I fix it?

EDIT:

I thought maybe it's because the target method is private, but I'm not so sure. From the DynamicMethod MSDN page:

The following code example creates a DynamicMethod that is logically associated with a type. This association gives it access to the private members of that type.

回答1:

Interesting issue. First there are few things you can do. If you only want a delegate for the setter you can use Delegate.CreateDelegate.

Delegate.CreateDelegate(typeof(Action<Foo, string>),typeof(Foo).GetProperty("A").GetSetMethod()) as Action<Foo,String>;

If you are using .NET 3.5+ you can use expression trees and I strongly recommend learning them over DynamicMethod, they have limited use in .NET 3.5 and almost none .NET 4. (TypeBuilder is still very useful though).

var targetExpression = Expression.Parameter(typeof(Foo),"target");
var valueExpression = Expression.Parameter(typeof(string),"value");
var expression = Expression.Lambda<Action<Foo,string>>(
      Expression.Call(
           targetExpression, 
           typeof(Foo).GetProperty("A").GetSetMethod(),
           valueExpression
      ),
      targetExpression,
      valueExpression
);

In .NET 4 you can write it to be slightly prettier by using Expression.Assign, but it's not much better.

Finally, if you really want to do it in IL this works.

        DynamicMethod method = new DynamicMethod("Setter", typeof(void), new[] { typeof(Foo), typeof(string) }, true);
        var ilgen = method.GetILGenerator();
        ilgen.Emit(OpCodes.Ldarg_0);
        ilgen.Emit(OpCodes.Ldarg_1);
        ilgen.Emit(OpCodes.Callvirt, typeof(Foo).GetProperty("A").GetSetMethod());
        ilgen.Emit(OpCodes.Ret);
        var action = method.CreateDelegate(typeof(Action<Foo,string>)) as Action<Foo,string>;

I think your issue is that you are currently calling the set method is actually the getMethod the error is on this line:: MethodInfo setMethod = typeof(Foo).GetMethod("get_" + propName);

I've never assigned parameter attributes but that may also be an issue too.



回答2:

Well I figured it out. Changing

IL.Emit(OpCodes.Callvirt, setMethod);

to

IL.Emit(OpCodes.Call, setMethod);

fixed it. I don't know why the disassembly showed CallVirt, but eh.



回答3:

What version of .NET does this need to run on? Compiling a delegate from an expression tree would be much easier.