在C#中动态生成委托类型 [英] Generating Delegate Types dynamically in C#

查看:1118
本文介绍了在C#中动态生成委托类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有我们需要动态生成委托类型的要求。
我们需要生成给定的输入参数和输出的代表。输入和输出是简单类型。

We have a requirement where we need to generate delegate types on the fly. We need to generate delegates given the input parameters and the output. Both input and output would be simple types.

例如,我们需要生成

int Del(int, int, int, string)

int Del2(int, int, string, int)

这是如何让这个开始任何指针将是非常有益的。

Any pointers on how to get started on this would be very helpful.

我们需要分析其制定重新psented为XML $ P $。

We need to parse formulate which are represented as xml.

例如,我们重新present(A + B)为

For example, we represent (a + b) as

<ADD>
    <param type="decimal">A</parameter>
    <param type="decimal">B</parameter>
</ADD>

我们现在希望这暴露为 Func键&LT;小数,小数,小数&GT; 。我们当然希望允许在XML嵌套的节点,例如:

We now want this to be exposed as Func<decimal, decimal, decimal>. We of course want to allow nested nodes in the xml, e.g:

(a + b) + (a - b  * (c - d)))

我们要做到这一点使用前pression树木和防爆pression.Compile

We want to do this using expression trees and Expression.Compile.

这种方法的可行性建议,欢迎。

Suggestions on the feasibility of this approach are welcome.

推荐答案

最简单的方法是使用现有的函数功能家庭代表。

The simplest way would be to use the existing Func family of delegates.

使用的typeof(Func键&LT;&,,, GT)。MakeGenericType(...)。例如,对于您的 INT Del2(INT,INT,字符串,整数)类型:

Use typeof(Func<,,,,>).MakeGenericType(...). For example, for your int Del2(int, int, string, int) type:

using System;

class Test
{
    static void Main()
    {
        Type func = typeof(Func<,,,,>);
        Type generic = func.MakeGenericType
            (typeof(int), typeof(int), typeof(string),
             typeof(int), typeof(int));
        Console.WriteLine(generic);
    }
}

如果你真的,的真正的需要创建一个真正的新类型,也许你可以给一些更多的上下文来帮助我们来帮助你更好的。

If you really, really need to create a genuinely new type, perhaps you could give some more context to help us help you better.

编辑:Olsin说,在函数功能类型是.NET 3.5的一部分 - 但如果你想在使用他们的.NET 2.0中,你就必须声明它们自己,是这样的:

As Olsin says, the Func types are part of .NET 3.5 - but if you want to use them in .NET 2.0, you just have to declare them yourself, like this:

public delegate TResult Func<TResult>();
public delegate TResult Func<T, TResult>(T arg);
public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);
public delegate TResult Func<T1, T2, T3, TResult>
    (T1 arg1, T2 arg2, T3 arg3);
public delegate TResult Func<T1, T2, T3, T4, TResult>
    (T1 arg1, T2 arg2, T3 arg3, T4 arg4);

如果4个参数是不够的,你可以添加更多的,当然。

If 4 arguments isn't enough for you, you can add more of course.

这篇关于在C#中动态生成委托类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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