我正在尝试动态创建一个带有参数的空构造函数,并使用TypeBuilder简单地调用base(argument)。
我的代码类似于:
(...)
// Create a class derived from this class
TypeBuilder typeBuilder = moduleBuilder.DefineType("NewClass", TypeAttributes.Class, this.GetType());
ConstructorInfo baseCtor = this.GetType().GetConstructor(new[] { typeof(int) });
// Define new ctor taking int
ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(int) });
// Generate code to call base ctor passing int
ILGenerator ctorIL = constructorBuilder.GetILGenerator();
ctorIL.Emit(OpCodes.Ldarg_0);
ctorIL.Emit(OpCodes.Ldarg_1);
ctorIL.Emit(OpCodes.Call, baseCtor);
ctorIL.Emit(OpCodes.Ret);
// Generate derived class
Type type = typeBuilder.CreateType();
// Try to instantiate using new constructor
ConstructorInfo ctor = type.GetConstructor(new[] { typeof(int) });
object instance = ctor.Invoke(new object[] { 42 });
(...)
但总是没有抛出异常
System.Reflection.TargetInvocationException: NewClass..ctor(int32)
我做错了什么?
非常感谢您的任何帮助,
保罗