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

Generating Delegate Types dynamically in C#(在 C# 中动态生成委托类型)

本文介绍了在 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.

我们需要解析以xml表示的公式.

We need to parse formulate which are represented as xml.

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

For example, we represent (a + b) as

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

我们现在希望将其公开为 Func.我们当然希望在 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)))

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

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

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

Suggestions on the feasibility of this approach are welcome.

推荐答案

最简单的方法是使用现有的 Func 系列委托.

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

使用 typeof(Func<,,,,>).MakeGenericType(...).例如,对于您的 int Del2(int, int, string, 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 所说,Func 类型是 .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# 中动态生成委托类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 C# 中动态生成委托类型

基础教程推荐