DynamicMethod具有generics类型参数
是否可以使用generics类型参数定义DynamicMethod? MethodBuilder类具有DefineGenericParameters方法。 DynamicMethod有对应的吗? 例如,是否可以使用DynamicMethod创建具有签名的方法?
void T Foo(T a1, int a2)
实际上有一种方法,它不是通用的,但你会得到这个想法:
public delegate T Foo(T a1, int a2); public class Dynamic { public static readonly Foo Foo = GenerateFoo (); private static Foo GenerateFoo () { Type[] args = { typeof(V), typeof(int)}; DynamicMethod method = new DynamicMethod("FooDynamic", typeof(V), args); // emit it return (Foo )method.CreateDelegate(typeof(Foo )); } }
你可以这样称呼它:
Dynamic.Foo(1.0, 3);
这似乎不可能:正如您所见, DynamicMethod
没有DefineGenericParameters
方法,并且它从MethodInfo
基类inheritanceMakeGenericMethod
,它只抛出NotSupportedException
。
几种可能性:
- 使用
AppDomain.DefineDynamicAssembly
定义整个动态程序集 - 通过为每组类型参数生成一次相同的
DynamicMethod
,自己做generics