在C#中动态生成委托类型

我们有一个要求,我们需要动态生成委托类型。 我们需要根据输入参数和输出生成委托。 输入和输出都是简单类型。

例如,我们需要生成

int Del(int, int, int, string) 

 int Del2(int, int, string, int) 

任何关于如何开始这方面的指示都会非常有帮助。

我们需要解析表示为xml的表达式。

例如,我们将(a + b)表示为

  A B  

我们现在希望将其公开为Func 。 我们当然希望允许xml中的嵌套节点,例如:

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

我们希望使用表达式树和Expression.Compile来做到这一点。

欢迎就这种方法的可行性提出建议。

最简单的方法是使用现有的Func系列代理。

使用typeof(Func<,,,,>).MakeGenericType(...) 。 例如,对于你的int Del2(int, int, string, int)类型:

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

如果你真的, 真的需要创建一个真正的新类型,也许你可以提供一些更多的背景来帮助我们更好地帮助你。

编辑:正如Olsin所说, Func类型是.NET 3.5的一部分 – 但是如果你想在.NET 2.0中使用它们,你只需要自己声明它们,如下所示:

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

如果4个参数对您来说还不够,那么您当然可以添加更多参数。

如果您正在运行框架3.5(但不是每个人都是),Jon的答案可以正常运行。

2.0的答案是使用Delegate.CreateDelegate(…)

http://msdn.microsoft.com/en-us/library/system.delegate.createdelegate.aspx

在早期的一个post中讨论了各种方法的比较,包括Jon的Func,Delegate.CreateDelegate,DynamicMethods和各种其他技巧。

Delegate.CreateDelegate与DynamicMethod vs Expression

-Oisin