是的,你可以使用foreach
,並調用Invoke
動態 - 你需要輸入是動態的,以及雖然:
using System;
using System.Collections.Generic;
class Test
{
static void Main()
{
Func<int,int> fn1 = new Func<int,int>(x => 3);
Func<int,int> fn2 = new Func<int,int>(x => x + 3);
Func<int,int> fn3 = new Func<int,int>(x => x + 30);
Func<int,double> fn4 = new Func<int,double>(x => x * 0.2);
List<dynamic> pipeline = new List<dynamic> { fn1, fn2, fn3, fn4 };
dynamic current = 6;
foreach (dynamic stage in pipeline)
{
// current = stage(current) would work too, but I think it's less clear
current = stage.Invoke(current);
}
Console.WriteLine($"Result: {current}");
}
}
(這是奇怪的是,你的第一個功能,忽略輸入, )
請注意,這裏沒有編譯時類型的安全性 - 如果你的某個函數實際上需要一個字符串,那麼你只會在執行時發現它。如果不知道如何你在你的實際代碼創建的代表,很難確切地知道解決這個問題的最好辦法,但這裏有一個選項:
class Pipeline<TInput, TOutput>
{
private readonly Func<TInput, TOutput> function;
public Pipeline(Func<TInput, TOutput> function)
{
this.function = function;
}
public Pipeline<TInput, TNext> Then<TNext>(Func<TOutput, TNext> nextFunction) =>
new Pipeline<TInput, TNext>(input => nextFunction(function(input)));
public TOutput Process(TInput input) => function(input);
}
class Test
{
static void Main()
{
Pipeline<int, double> pipeline = new Pipeline<int, int>(x => 3)
.Then(x => x + 3)
.Then(x => x + 30)
.Then(x => x * 0.2);
var result = pipeline.Process(6);
Console.WriteLine($"Result: {result}");
}
}
是'.Invoke()'有必要嗎?簡單地說'stage(current)'有什麼區別?這似乎編譯和工作也很好。 –
@RenéVogt:我認爲它更清晰,就是這樣。將編輯澄清*,*。 –