gpt4 book ai didi

C# 流水线函数数组签名

转载 作者:太空狗 更新时间:2023-10-29 19:43:32 25 4
gpt4 key购买 nike

c# 的类型系统是否能够指定一个函数,该函数采用可枚举数量的函数,这些函数交换形成管道?

效果类似于链接,但不是

var pipeline = a.Chain(b).Chain(c)

可以写

var pipeline = CreatePipeline(a,b,c)

其中 a、b 和 c 是函数?我已经包含了一些示例代码来说明,谢谢。

void Main()
{
Func<int, string> a = i => i.ToString();
Func<string, DateTime> b = s => new DateTime(2000,1,1).AddDays(s.Length);
Func<DateTime, bool> c = d => d.DayOfWeek == DayOfWeek.Wednesday;

//var myPipeline = CreatePipeline(a, b, c);

Func<int, bool> similarTo = i => c(b(a(i))) ;

Func<int, bool> isThisTheBestWeCanDo = a.Chain(b).Chain(c);

}

public static class Ext{

//public static Func<X, Z> CreatePipeline<X,Z>(params MagicFunc<X..Y>[] fns) {
// return
//}

public static Func<X, Z> Chain<X,Y,Z>(this Func<X,Y> a, Func<Y,Z> b)
{
return x => b(a(x));
}
}

最佳答案

可以考虑this solution :

public class Pipeline
{
public Func<object, object> CreatePipeline(params Func<object, object>[] funcs)
{
if (funcs.Count() == 1)
return funcs[0];

Func<object, object> temp = funcs[0];
foreach (var func in funcs.Skip(1))
{
var t = temp;
var f = func;
temp = x => f(t(x));
}
return temp;
}
}

用法:

Func<int, string> a = x => (x * 3).ToString();
Func<string, bool> b = x => int.Parse(x.ToString()) / 10 > 0;
Func<bool, bool> c = x => !x;

var pipeline = new Pipeline();
var func = pipeline.CreatePipeline(x => a((int)x), x => b((string)x), x => c((bool)x));

Console.WriteLine(func(3));//True
Console.WriteLine(func(4));//False

关于C# 流水线函数数组签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50472593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com