与泛型类型参数DynamicMethod的 [英] DynamicMethod with generic type parameters

查看:279
本文介绍了与泛型类型参数DynamicMethod的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 无效牛逼美孚< T>( ŧA1,INT A2)


解决方案

其实还有一种方法,它不完全通用的,但你会得到的想法:

 公共委托牛逼美孚< T>(T A1,诠释A2 ); 

公共类动态< T>
{
公共静态只读美孚< T>美孚= GenerateFoo< T>();

私有静态美孚< V> GenerateFoo< V>()
{
类型[] ARGS = {typeof运算(V)的typeof(INT)};

DynamicMethod的方法=
新DynamicMethod的(FooDynamic的typeof(V),参数);

//发出它

回报率(美孚< V>)method.CreateDelegate(typeof运算(富< V>));
}
}

您可以调用它是这样的:

 动态<双>包含.foo(1.0,3); 


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)

解决方案

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

这篇关于与泛型类型参数DynamicMethod的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆