Dan*_*cco 2 c# reflection.emit
我正在尝试使用Emit在动态方法中创建一个新的List <>对象:
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);
}
Run Code Online (Sandbox Code Playgroud)
我已经检查了我试图使用ILDasm实现的代码,并且这些OpCode似乎是正确的,所以我猜这是我在尝试获取泛型类型的构造函数时做错了.
我做错了什么,我怎么能这样做?
编辑:此行发生错误:
// - Type is the custom type created in runtime
Activator.CreateInstance(Type);
Run Code Online (Sandbox Code Playgroud)
错误消息: mscorlib.dll中发生未处理的"System.Reflection.TargetInvocationException"类型异常
附加信息:目标抛出异常.
内部异常:公共语言运行时检测到无效程序.
堆栈跟踪: 在TestObjectProxy..ctor()
小智 6
Run Code Online (Sandbox Code Playgroud)// - Calling the base constructor ilGen.Emit(OpCodes.Call, constructorInfo);
那不完整.基础构造函数调用是对基类的实例方法的常规调用,因此Ldarg_0在此之前需要另一个.
| 归档时间: |
|
| 查看次数: |
852 次 |
| 最近记录: |