Ale*_*lex 8 c# reflection reflection.emit dynamicmethod
是否可以使用泛型类型参数定义DynamicMethod?MethodBuilder类具有DefineGenericParameters方法.DynamicMethod有对应的吗?例如,是否可以使用DynamicMethod创建具有签名的方法?
void T Foo<T>(T a1, int a2)
Run Code Online (Sandbox Code Playgroud)
这似乎不可能:正如您所见DynamicMethod,没有DefineGenericParameters方法,它继承MakeGenericMethod自其MethodInfo基类,它只是抛出NotSupportedException.
几种可能性:
AppDomain.DefineDynamicAssemblyDynamicMethod为每组类型参数生成相同的一次来自己做泛型实际上有一种方法,它并不完全通用,但你会明白的:
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>));
}
}
Run Code Online (Sandbox Code Playgroud)
你可以这样称呼它:
Dynamic<double>.Foo(1.0, 3);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1367 次 |
| 最近记录: |