DynamicMethod with generic type parameters

霸气de小男生 提交于 2019-12-29 07:40:06

问题


Is it possible to define a DynamicMethod with generic type parameters? The MethodBuilder class has the DefineGenericParameters method. Does the DynamicMethod have a counterpart? For example is it possible to create method with a signature like the one given blow using DynamicMethod?

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

回答1:


Actually there is a way, it's not exactly generic but you'll get the idea:

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>));
    }
}

You can call it like this:

Dynamic<double>.Foo(1.0, 3);



回答2:


This doesn't appear to be possible: as you've seen DynamicMethod has no DefineGenericParameters method, and it inherits MakeGenericMethod from its MethodInfo base class, which just throws NotSupportedException.

A couple of possibilities:

  • Define a whole dynamic assembly using AppDomain.DefineDynamicAssembly
  • Do generics yourself, by generating the same DynamicMethod once for each set of type arguments


来源:https://stackoverflow.com/questions/788618/dynamicmethod-with-generic-type-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!