我有以下课程:
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被传递给实例,但我不知道为什么!?