Can you chain the result of one delegate to be the input of another in C#?

前端 未结 5 1110
春和景丽
春和景丽 2021-01-14 13:09

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 ar

5条回答
  •  佛祖请我去吃肉
    2021-01-14 14:01

    This might help:

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

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

    Func floor = Math.Floor;
    Func convertToInt = Convert.ToInt32;
    
    Func floorAndConvertToInt = Compose(floor, convertToInt);
    
    int result = floorAndConvertToInt(5.62);
    
    Func floorThenConvertThenAddTen = Compose(floorAndConvertToInt, i => i + 10);
    
    int result2 = floorThenConvertThenAddTen(64.142);
    

提交回复
热议问题