您可以将一个委托的结果链接为C#中另一个的输入吗? [英] Can you chain the result of one delegate to be the input of another in C#?

查看:105
本文介绍了您可以将一个委托的结果链接为C#中另一个的输入吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种链接多个代表的方法,以便使一个代表的结果成为下一个代表的输入。我正在尝试在方程求解程序中使用此函数,其中部分通过不同的方法完成。这个想法是,当您构建方程式时,程序会添加代表并按特定顺序将它们链接起来,因此可以正确解决。如果有更好的方法可以解决此问题,请分享。

I am looking for a way to chain several delegates so the result from one becomes the input of the next. I am trying to use this in equation solving program where portions are done by different methods. The idea is that when you are building the equation the program adds the delegates and chains them in a particular order, so it can be solved properly. If there is a better way to approach the problem please share.

推荐答案

这可能有帮助:

public static Func<T1, TResult> Compose<T1, T2, TResult>(Func<T1, T2> innerFunc, Func<T2, TResult> outerFunc) {
    return arg => outerFunc(innerFunc(arg));
}

此操作执行函数组合,运行 innerFunc 并将结果传递给 outerFunc 当提供初始参数时:

This performs function composition, running innerFunc and passing the result to outerFunc when the initial argument is supplied:

Func<double, double> floor = Math.Floor;
Func<double, int> convertToInt = Convert.ToInt32;

Func<double, int> floorAndConvertToInt = Compose(floor, convertToInt);

int result = floorAndConvertToInt(5.62);

Func<double, int> floorThenConvertThenAddTen = Compose(floorAndConvertToInt, i => i + 10);

int result2 = floorThenConvertThenAddTen(64.142);

这篇关于您可以将一个委托的结果链接为C#中另一个的输入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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