是否可以使用泛型类型参数定义 DynamicMethod?MethodBuilder 类具有 DefineGenericParameters 方法。DynamicMethod 有对应的吗?例如,是否可以使用 DynamicMethod 创建具有像给定打击一样的签名的方法?
void T Foo<T>(T a1, int a2)
是否可以使用泛型类型参数定义 DynamicMethod?MethodBuilder 类具有 DefineGenericParameters 方法。DynamicMethod 有对应的吗?例如,是否可以使用 DynamicMethod 创建具有像给定打击一样的签名的方法?
void T Foo<T>(T a1, int a2)
这似乎是不可能的:正如你所看到的,它DynamicMethod
没有DefineGenericParameters
方法,它继承MakeGenericMethod
自它的MethodInfo
基类,它只是 throws NotSupportedException
。
几种可能性:
AppDomain.DefineDynamicAssembly
DynamicMethod
为每组类型参数生成一次实际上有一种方法,它并不完全通用,但你会明白的:
public delegate T Foo<T>(T a1, int a2);
public class Dynamic<T>
{
public static readonly Foo<T> Foo = GenerateFoo<T>();
private static Foo<V> GenerateFoo<V>()
{
Type[] args = { typeof(V), typeof(int)};
DynamicMethod method =
new DynamicMethod("FooDynamic", typeof(V), args);
// emit it
return (Foo<V>)method.CreateDelegate(typeof(Foo<V>));
}
}
你可以这样称呼它:
Dynamic<double>.Foo(1.0, 3);