3

我有以下课程:

private sealed class Person
{
    public string Name { get; }
    public int Age { get; }

    public Person(string name)
    {
        Name = name;
    }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

以及以下动态创建 a 实例的方法ConstructorInfo

public static Func<object[], T> GetBuilder<T>(ConstructorInfo constructor)
{
    var type = constructor.ReflectedType;    
    var ctorParams = constructor.GetParameters();

    var dynamicMethod = new DynamicMethod("Create_" + constructor.Name, type, new[] { typeof(object[]) }, type, true);
    var ilGen = dynamicMethod.GetILGenerator();

    /*
     * Cast each argument of the input object array to the appropriate type
     * The order of objects should match the order set by the Ctor
     * It is also assumed the length of object array args is same length as Ctor args. 
     * Exceptions for the delegate that mean the above weren't satisfied: 
     * InvalidCastException, IndexOutOfRangeException
     */
    for (var i = 0; i < ctorParams.Length; i++)
    {
        // Push Object array
        ilGen.Emit(OpCodes.Ldarg_0);

        // Push the index to access
        ilGen.Emit(OpCodes.Ldc_I4, i);

        // Push the element at the previously loaded index
        ilGen.Emit(OpCodes.Ldelem_Ref);

        // Cast the object to the appropriate Ctor Parameter Type
        var paramType = ctorParams[i].ParameterType;
        ilGen.Emit(paramType.IsValueType ? OpCodes.Box : OpCodes.Castclass, paramType);
    }

    // Call the Ctor, all values on the stack are passed to the Ctor
    ilGen.Emit(OpCodes.Newobj, constructor);
    // Return the new object
    ilGen.Emit(OpCodes.Ret);

    // Create delegate from our IL, cast and return
    return (Func<object[], T>)dynamicMethod.CreateDelegate(typeof(Func<object[], T>));
}

然后我使用该方法为每个构造函数创建这个类的两个实例:

var ctorOne = typeof(Person).GetConstructors(BindingFlags.Public | BindingFlags.Instance)[0];
var instanceBuilderOne = GetBuilder<Person>(publicCtor[0]);
var instanceOne = instanceBuilderOne(new object[] { "Foo"});
instanceOne.Name.Dump(); // is "Foo"

var ctorTwo = typeof(Person).GetConstructors(BindingFlags.Public | BindingFlags.Instance)[1];
var instanceBuilderTwo = GetBuilder<Person>(publicCtor[1]);
var instanceTwo = instanceBuilderTwo(new object[] { "Bar", 1});
instanceTwo.Name.Dump(); // is "Bar"
instanceTwo.Age.Dump(); // is 43603896

然而,我得到43603896instanceTwo而不是得到1

在相关构造函数中点击断点确实显示43603896被传递给实例,但我不知道为什么!?

4

1 回答 1

4

首先,OpCodes.Box这里显然是错误的,因为您想从对象中拆箱 int,而不是装箱。

现在OpCodes.Unbox它的作用是取消装箱值并将对未装箱值的引用推送到堆栈。该参考是您所看到的,而不是“1”。如果要使用OpCodes.Unbox,正确的方法是:

if (paramType.IsValueType) {
     ilGen.Emit(OpCodes.Unbox, paramType);
     ilGen.Emit(OpCodes.Ldobj, paramType);
}
else {
      ilGen.Emit(OpCodes.Castclass, paramType);
}

但更容易使用OpCodes.Unbox_Any,它基本上会做同样的事情,但在一行中:

ilGen.Emit(OpCodes.Unbox_Any, paramType);
于 2016-12-16T21:14:13.760 回答