简体   繁体   English

Reflection.Emit和泛型类型

[英]Reflection.Emit and generic types

I am using Reflection.Emit and I want to create a type that would be the equivalent of the following type defined in C#: 我正在使用Reflection.Emit ,我想创建一个类似于C#中定义的以下类型的类型:

class A
{
    public Tuple<A, int> GetValue(int x)
    {
         return new Tuple<A, int>(this, x);
    }
}

The trick is that I need to use a generic type from BCL that uses my custom type as a generic argument. 诀窍是我需要使用BCL中的泛型类型,它使用我的自定义类型作为泛型参数。

I'm messing with the following snippet: 我正在搞乱以下片段:

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);

The call to GetConstructor fails with the following exception: GetConstructor的调用失败,出现以下异常:

NotSupportedException: Specified method is not supported. NotSupportedException:不支持指定的方法。

So, basically, it won't let me get the constructor of a type that merely references my custom type, and neither can I finalize the type before emitting the body of its method. 所以,基本上,它不会让我获得仅仅引用我的自定义类型的类型的构造函数,也不能在发出其方法的主体之前最终确定类型。

Can it really be impossible to get out of this vicious circle? 真的不可能走出这个恶性循环吗?

For some reason, you need to use the static overload of GetConstructor() to do this. 出于某种原因,您需要使用GetConstructor()的静态重载来执行此操作。 In your case, the code could look like this: 在您的情况下,代码可能如下所示:

var ctor = TypeBuilder.GetConstructor(
    tupleType, typeof(Tuple<,>).GetConstructors().Single());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM