I am trying to dynamically create an empty constructor that takes an argument and simply calls the base (argument) using TypeBuilder.
My code looks something like this:
(...)
TypeBuilder typeBuilder = moduleBuilder.DefineType("NewClass", TypeAttributes.Class, this.GetType());
ConstructorInfo baseCtor = this.GetType().GetConstructor(new[] { typeof(int) });
ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(int) });
ILGenerator ctorIL = constructorBuilder.GetILGenerator();
ctorIL.Emit(OpCodes.Ldarg_0);
ctorIL.Emit(OpCodes.Ldarg_1);
ctorIL.Emit(OpCodes.Call, baseCtor);
ctorIL.Emit(OpCodes.Ret);
Type type = typeBuilder.CreateType();
ConstructorInfo ctor = type.GetConstructor(new[] { typeof(int) });
object instance = ctor.Invoke(new object[] { 42 });
(...)
but always ignores the exception.
System.Reflection.TargetInvocationException: NewClass..ctor(int32)
What am I doing wrong?
Thanks so much for any help,
Paolo
source
share