Imp*_*rks 4 c# reflection.emit
我正在使用Reflection.Emit,我想创建一个类似于C#中定义的以下类型的类型:
class A
{
public Tuple<A, int> GetValue(int x)
{
return new Tuple<A, int>(this, x);
}
}
Run Code Online (Sandbox Code Playgroud)
诀窍是我需要使用BCL中的泛型类型,它使用我的自定义类型作为泛型参数.
我正在搞乱以下片段:
var asmName = new AssemblyName("Test");
var access = AssemblyBuilderAccess.Run;
var asm = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, access);
var module = asm.DefineDynamicModule("Test");
var aType = module.DefineType("A");
var tupleType = typeof(Tuple<,>).MakeGenericType(aType, typeof(int));
var attrs = MethodAttributes.Public;
var method = aType.DefineMethod("GetValue", attrs, tupleType, new [] { typeof(int) });
var gen = method.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_1);
// here is the fail:
var ctor = tupleType.GetConstructor(new [] { typeof(int), aType } );
gen.Emit(OpCodes.Newobj, ctor);
Run Code Online (Sandbox Code Playgroud)
调用GetConstructor失败,出现以下异常:
NotSupportedException:不支持指定的方法.
所以,基本上,它不会让我获得仅仅引用我的自定义类型的类型的构造函数,也不能在发出其方法的主体之前最终确定类型.
真的不可能走出这个恶性循环吗?
出于某种原因,您需要使用静态重载GetConstructor()来执行此操作.在您的情况下,代码可能如下所示:
var ctor = TypeBuilder.GetConstructor(
tupleType, typeof(Tuple<,>).GetConstructors().Single());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
772 次 |
| 最近记录: |