8

是否可以使用泛型类型参数定义 DynamicMethod?MethodBuilder 类具有 DefineGenericParameters 方法。DynamicMethod 有对应的吗?例如,是否可以使用 DynamicMethod 创建具有像给定打击一样的签名的方法?

void T Foo<T>(T a1, int a2)
4

2 回答 2

7

这似乎是不可能的:正如你所看到的,它DynamicMethod没有DefineGenericParameters方法,它继承MakeGenericMethod自它的MethodInfo基类,它只是 throws NotSupportedException

几种可能性:

  • 使用定义一个完整的动态程序集AppDomain.DefineDynamicAssembly
  • 自己做泛型,DynamicMethod为每组类型参数生成一次
于 2009-04-25T11:59:21.090 回答
3

实际上有一种方法,它并不完全通用,但你会明白的:

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);
于 2014-03-26T04:35:17.147 回答