Generating a constructor that takes an argument and just calls base(argument) using TypeBuilder

穿精又带淫゛_ 提交于 2019-12-07 05:19:19

问题


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 exception
System.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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!