2017-08-07 81 views
0

我想創建方法列表。並按順序運行這個方法列表。 下一個方法的輸入是當前方法的輸出。如何獲取輸入和返回類型的代碼存儲在列表中<dynamic>在C#中?

所以,這是我的代碼爲這些,我需要得到輸入,輸出類型。

static void Main(string [ ] args) 
{ 
    List<dynamic> temp = new List<dynamic>(); 

    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); 

    temp.Add(fn1); 
    temp.Add(fn2); 
    temp.Add(fn3); 
    temp.Add(fn4); 

    int input = 6; 
    // use for or foreach or something 
    // output ? 
} 

回答

3

是的,你可以使用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}"); 
    } 
} 
+0

是'.Invoke()'有必要嗎?簡單地說'stage(current)'有什麼區別?這似乎編譯和工作也很好。 –

+0

@RenéVogt:我認爲它更清晰,就是這樣。將編輯澄清*,*。 –

相關問題