问题
I am trying to dynamically create an empty constructor that takes an argument and simply calls base(argument) using TypeBuilder.
My code is something like:
(...)
// 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 });
(...)
but is always failing throwing an exceptionSystem.Reflection.TargetInvocationException: NewClass..ctor(int32)
What am I doing wrong?
Many thanks in advance for any help,
Paolo
来源:https://stackoverflow.com/questions/8419839/generating-a-constructor-that-takes-an-argument-and-just-calls-baseargument-us