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));
}
}
答案 0 :(得分:3)
您可以考虑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