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.

eg, we need to generate

int Del(int, int, int, string)

and

int Del2(int, int, string, int)

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

We need to parse formulate which are represented as xml.

For example, we represent (a + b) as

A

B

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

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

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.

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.

EDIT: 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();

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值