IL Emit调用泛型类型构造函数?

时间:2014-12-29 18:42:12

标签: c# reflection.emit

我正在尝试创建一个新列表<>使用Emit的动态方法中的对象:

Type original; // original is a type passed

AssemblyName assemblyName = new AssemblyName("CustomAssembly");
AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
ModuleBuilder _moduleBuilder = assembly.DefineDynamicModule("CustomModule");

// - IProxy can be ignored for this example
TypeBuilder typeBuilder = _moduleBuilder.DefineType(original.Name + "Proxy", TypeAttributes.Public | TypeAttributes.Class, original, new Type[] { typeof(IProxy) });

// - Getting the type of List<Interceptor>
Type interceptorList = typeof(List<>).MakeGenericType(typeof(Interceptor));
// - Setting a 'private List<Interceptor> _interceptors;'
FieldBuilder interceptorField = typeBuilder.DefineField("_interceptors", interceptorList, FieldAttributes.Private);
// - Getting the default constructor 'new List<Interceptor>()'
ConstructorInfo interceptorConstructor = interceptorList.GetConstructor(Type.EmptyTypes);
// - And the '.Add(Interceptor interceptor)' method
MethodInfo addInterceptor = interceptorList.GetMethod("Add", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(Interceptor) }, null);

foreach (ConstructorInfo constructorInfo in original.GetConstructors())
{
    ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.HideBySig, CallingConventions.Standard, parameters);
    ILGenerator ilGen = constructorBuilder.GetILGenerator();
    ilGen.Emit(OpCodes.Ldarg_0); //[this]

    //These two lines cause an exception when I try to create this custom type        
    ilGen.Emit(OpCodes.Newobj, interceptorConstructor); //[new List<Interceptor>();]
    ilGen.Emit(OpCodes.Stfld, interceptorField); //[_interceptors = new List<Interceptor>();]

    // - Calling the base constructor
    ilGen.Emit(OpCodes.Call, constructorInfo);
    ilGen.Emit(OpCodes.Ret);
}

我已经检查了我试图使用ILDasm实现的代码,并且这些OpCode似乎是正确的,所以我猜这是我在尝试获取泛型类型的构造函数时做错了。< / p>

我做错了什么,我怎样才能使这个工作?

修改:此行发生错误:

// - Type is the custom type created in runtime
Activator.CreateInstance(Type);

错误消息: mscorlib.dll中出现未处理的“System.Reflection.TargetInvocationException”类型异常

其他信息:目标已抛出异常。

内部异常:公共语言运行时检测到无效程序。

在TestObjectProxy..ctor()

堆栈跟踪:

1 个答案:

答案 0 :(得分:6)

// - Calling the base constructor
ilGen.Emit(OpCodes.Call, constructorInfo);

那不完整。基础构造函数调用是对基类的实例方法的常规调用,因此在它之前需要另一个Ldarg_0