使用Reflection.Emit 生成动态类,如何调用基类中的带参数的构造函数?

tylike 2009-10-15 12:30:23
// create a new type builder
var typeBuilder = Module.DefineType(TypeName, TypeAttributes.Public | TypeAttributes.Class, baseClass);
var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Any , new Type[] { typeof(Session) });
var baseCtor = baseClass.GetConstructor(new Type[] { typeof(Session) });

var ilGenerator = ctor.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.Emit(OpCodes.Ldarg_1);
//这里调用不对吗?
ilGenerator.Emit(OpCodes.Call, baseCtor);
ilGenerator.Emit(OpCodes.Nop);
ilGenerator.Emit(OpCodes.Nop);
ilGenerator.Emit(OpCodes.Nop);
ilGenerator.Emit(OpCodes.Ret);
return typeBuilder.CreateType();
//报错:
//Unable to create an instance of the "Test1" type.
Reason: "不支持所指定的方法。",

stack trace: " 在 System.Reflection.RuntimeConstructorInfo.CheckCanCreateInstance(Type declaringType, Boolean isVarArg)
在 System.Reflection.RuntimeConstructorInfo.ThrowNoInvokeException()
在 System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
在 System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
在 System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
在 DevExpress.ExpressApp.DC.TypeInfo.CreateInstance(Object[] args)"
end stack trace

//我希望得到下面的IL代码:
//.maxstack 8
//L_0000: ldarg.0
//L_0001: ldarg.1
//L_0002: call instance void [DevExpress.Persistent.BaseImpl.v9.2]DevExpress.Persistent.BaseImpl.BaseObject::.ctor(class [DevExpress.Xpo.v9.2]DevExpress.Xpo.Session)
//L_0007: nop
//L_0008: nop
//L_0009: nop
//L_000a: ret
...全文
172 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
tylike 2009-10-15
  • 打赏
  • 举报
回复
^

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧