Reflection.Emit的和泛型类型 [英] Reflection.Emit and generic types
问题描述
我使用 Reflection.Emit的
,我想创建一个类型,这将是在C#中定义以下类型的等效:
I am using Reflection.Emit
and I want to create a type that would be the equivalent of the following type defined in C#:
class A
{
public Tuple<A, int> GetValue(int x)
{
return new Tuple<A, int>(this, x);
}
}
诀窍是,我需要使用泛型类型。从使用我的自定义类型作为一般的参数BCL
The trick is that I need to use a generic type from BCL that uses my custom type as a generic argument.
我用下面的代码片段搞乱:
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);
到 GetConstructor
的调用失败,出现以下例外:
The call to GetConstructor
fails with the following exception:
NotSupportedException异常:不支持指定的方法。
NotSupportedException: Specified method is not supported.
所以,基本上,它不会让我得到一个类型,仅仅是引用我的自定义类的构造函数,也不我能完成它的发光方法的主体之前的类型。
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?
推荐答案
由于某些原因,您需要使用 的静态超载GetConstructor()
来做到这一点。在你的情况,代码看起来是这样的:
For some reason, you need to use the static overload of GetConstructor()
to do this. In your case, the code could look like this:
var ctor = TypeBuilder.GetConstructor(
tupleType, typeof(Tuple<,>).GetConstructors().Single());
这篇关于Reflection.Emit的和泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!