问题描述
我正在寻找一种方法来链接多个委托,以便一个委托的结果成为下一个委托的输入.我试图在方程求解程序中使用它,其中部分是通过不同的方法完成的.这个想法是,当您构建方程式时,程序会添加代表并以特定顺序将它们链接起来,因此可以正确求解.如果有更好的方法来解决这个问题,请分享.
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# 中另一个委托的输入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!