C#管道式編程的介紹與實現

這篇文章主要給大家介紹了關於C#管道式編程的介紹與實現方法,文中通過示例代碼介紹的非常詳細,對大家學習或者使用C#具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧

受 F# 中的管道運算符和 C# 中的 LINQ 語法,管道式編程爲 C# 提供了更加靈活性的功能性編程。通過使用 擴展函數 可以將多個功能連接起來構建成一個管道。

前言

在 C# 編程中,管道式編程(Pipeline Style programming)其實存在已久,最明顯的就是我們經常使用的 LINQ。在進入 DotNetCore 世界後, 這種編程方式就更加明顯,比如各種中間件的使用。通過使用這種編程方式,大大提高了代碼的可維護性,優化了的業務的組合方式。

管道式編程具有如下優點:

  • 創建一個流暢的編程範例,將語句轉換爲表達式並將它們鏈接在一起
  • 用線性排序替換代碼嵌套
  • 消除變量聲明 - 甚至不需要 var
  • 提供某種形式的可變不變性和範圍隔離
  • 將結構代碼編寫成具有明確職責的小 lambda 表達式
  • ......

初體驗

基礎實現

在該示例中,我們通過構建一個 double->int->string 的類型轉換的管道來將一個目標數據最終轉化爲一個字符串。

首先,我們需要定義一個功能接口,用於約束每個功能函數的具體實現,示例代碼如下所示:

public interface IPipelineStep<INPUT, OUTPUT>
{
 OUTPUT Process(INPUT input);
}

然後,我們定義兩個類型轉換的功能類,繼承並實現上述接口,示例代碼如下所示:

public class DoubleToIntStep : IPipelineStep<double, int>
{
 public int Process(double input)
 {
 return Convert.ToInt32(input);
 }
}

public class IntToStringStep : IPipelineStep<int, string>
{
 public string Process(int input)
 {
 return input.ToString();
 }
}

接着,定義一個擴展函數,用於連接上述的各個功能函數,示例代碼如下所示:

public static class PipelineStepExtensions
{
 public static OUTPUT Step<INPUT, OUTPUT>(this INPUT input, IPipelineStep<INPUT, OUTPUT> step)
 {
 return step.Process(input);
 }
}

最後,我們就可以構建一個完整的管道,用於我們的數據類型轉換,示例代碼如下所示:

class Program
{
 static void Main(string[] args)
 {
 double input = 1024.1024;

 // 構建並使用管道
 string result = input.Step(new DoubleToIntStep())
    .Step(new IntToStringStep());
 Console.WriteLine(result);
 }
}

此時,我們成功將一個 double 類型的數據轉化爲了 string 類型。通過介紹上述示例,我們可以簡單將管道式編程概括爲:定義功能接口 -> 實現功能函數 -> 組裝功能函數 。

依賴注入

上述代碼在一般的情況下是可以正常運行的,但是如果希望以 依賴注入(DI) 的方式注入的話,我們就需要將我們的管道組裝進行封裝,方便作爲一個統一的服務注入到系統中。

首先,我們需要定義一個抽線類,用於管道組裝的抽象封裝,示例代碼如下所示:

public abstract class Pipeline<INPUT,OUTPUT>
{
 public Func<INPUT, OUTPUT> PipelineSteps { get; protected set; }

 public OUTPUT Process(INPUT input)
 {
 return PipelineSteps(input);
 }
}

然後,我們就可以創建一個繼承上述抽象類的具體管道組裝類,示例代碼如下所示:

public class TrivalPipeline : Pipeline<double, string>
{
 public TrivalPipeline()
 {
 PipelineSteps = input => input.Step(new DoubleToIntSetp())
     .Step(new IntToStringStep());
 }
}

最後,我們可以將 TrivalPipeline 這個具體的管道注入到我們的系統中。同樣的,我們也可以直接使用,示例代碼如下所示:

class Program
{
 static void Main(string[] args)
 {
 double input = 1024.1024;

 // 需要安裝 Microsoft.Extensions.DependencyInjection
 var services = new ServiceCollection();
 services.AddTransient<TrivalPipeline>();
 var provider = services.BuildServiceProvider();

 var trival = provider.GetService<TrivalPipeline>();
 string result = trival.Process(input);
 Console.WriteLine(result);
 }
}

條件式組裝

上述兩個示例代碼展示的管道組裝式不帶任何條件限制的, 無論參數是否合法都是這樣組裝進管道,但是在實際的開發過程中,我們需要對一定的業務模塊進行條件性組裝,所以這個時候我們就需要完善一下我們的代碼。

首先,我們需要修改上面的 Pipeline<INPUT,OUTPUT> 類,使其繼承 IPipelineStep<INPUT, OUTPUT> 接口,示例代碼如下所示:

public abstract class Pipeline<INPUT, OUTPUT> : IPipelineStep<INPUT, OUTPUT>
{
 public Func<INPUT, OUTPUT> PipelineSteps { get; protected set; }

 public OUTPUT Process(INPUT input)
 {
 return PipelineSteps(input);
 }
}

然後,我們定義一個帶條件的管道裝飾器類,示例代碼如下所示:

public class OptionalStep<INPUT, OUTPUT> : IPipelineStep<INPUT, OUTPUT> where INPUT : OUTPUT
{
 private readonly IPipelineStep<INPUT, OUTPUT> _step;
 private readonly Func<INPUT, bool> _choice;

 public OptionalStep(Func<INPUT,bool> choice,IPipelineStep<INPUT,OUTPUT> step)
 {
 _choice = choice;
 _step = step;
 }

 public OUTPUT Process(INPUT input)
 {
 return _choice(input) ? _step.Process(input) : input;
 }
}

接着,我們定義一個新的功能類和支持條件判斷的管道包裝類,示例代碼如下所示:

public class ThisStepIsOptional : IPipelineStep<double, double>
{
 public double Process(double input)
 {
 return input * 10;
 }
}

public class PipelineWithOptionalStep : Pipeline<double, double>
{
 public PipelineWithOptionalStep()
 {
 // 當輸入參數大於 1024,執行 ThisStepIsOptional() 功能
 PipelineSteps = input => input.Step(new OptionalStep<double, double>(i => i > 1024, new ThisStepIsOptional()));
 }
}

最後,我們可以使用如下方式進行測試:

class Program
{
 static void Main(string[] args)
 {
 PipelineWithOptionalStep step = new PipelineWithOptionalStep();
 Console.WriteLine(step.Process(1024.1024)); // 輸出 10241.024
 Console.WriteLine(step.Process(520.520)); // 輸出 520.520
 }
}

事件監聽

有的時候,我們希望在我們管道中執行的每一步,在開始和結束時,上層模塊都能獲得相應的事件通知,這個時候,我們就需要需改一下我們的管道包裝器,使其支持這個需求。

首先,我們需要實現一個支持事件監聽的具體功能類,示例代碼代碼如下所示:

public class EventStep<INPUT, OUTPUT> : IPipelineStep<INPUT, OUTPUT>
{
 public event Action<INPUT> OnInput;
 public event Action<OUTPUT> OnOutput;

 private readonly IPipelineStep<INPUT, OUTPUT> _innerStep;
 public EventStep(IPipelineStep<INPUT,OUTPUT> innerStep)
 {
 _innerStep = innerStep;
 }

 public OUTPUT Process(INPUT input)
 {
 OnInput?.Invoke(input);

 var output = _innerStep.Process(input);

 OnOutput?.Invoke(output);

 return output;
 }
}

然後,我們需要定義一個能夠傳遞事件參數的管道包裝器類,示例代碼如下所示:

public static class PipelineStepEventExtensions
{
 public static OUTPUT Step<INPUT, OUTPUT>(this INPUT input, IPipelineStep<INPUT, OUTPUT> step, Action<INPUT> inputEvent = null, Action<OUTPUT> outputEvent = null)
 {
 if (inputEvent != null || outputEvent != null)
 {
  var eventDecorator = new EventStep<INPUT, OUTPUT>(step);
  eventDecorator.OnInput += inputEvent;
  eventDecorator.OnOutput += outputEvent;

  return eventDecorator.Process(input);
 }
 return step.Process(input);
 }
}

最後,上層調用就相對簡單很多,示例代碼如下所示:

public class DoubleStep : IPipelineStep<int, int>
{
 public int Process(int input)
 {
 return input * input;
 }
}

class Program
{
 static void Main(string[] args)
 {
 var input = 10;
 Console.WriteLine($"Input Value:{input}[{input.GetType()}]");
 var pipeline = new EventStep<int, int>(new DoubleStep());
 pipeline.OnInput += i => Console.WriteLine($"Input Value:{i}");
 pipeline.OnOutput += o => Console.WriteLine($"Output Value:{o}");
 var output = pipeline.Process(input);
 Console.WriteLine($"Output Value: {output} [{output.GetType()}]");
 Console.WriteLine("\r\n");

 //補充:使用擴展方法進行調用
 Console.WriteLine(10.Step(new DoubleStep(), i => 
 {
  Console.WriteLine($"Input Value:{i}");
 }, 
 o => 
 {
  Console.WriteLine($"Output Value:{o}");
 }));
 }
}

輸出結果如下圖所示:

可迭代執行

可迭代執行是指當我們的管道中註冊了多個功能模塊時,不是一次性執行完所以的功能模塊,而是每次只執行一個功能,後續功能會在下次執行該管道對應的代碼塊時接着執行,直到該管道中所有的功能模塊執行完畢爲止。該特性主要是通過 yield return 來實現。

首先,我們需要實現一個該特性的管道包裝器類,示例代碼如下所示:

public class LoopStep<INPUT, OUTPUT> : IPipelineStep<IEnumerable<INPUT>, IEnumerable<OUTPUT>>
{
 private readonly IPipelineStep<INPUT, OUTPUT> _internalStep;
 public LoopStep(IPipelineStep<INPUT,OUTPUT> internalStep)
 {
  _internalStep = internalStep;
 }

 public IEnumerable<OUTPUT> Process(IEnumerable<INPUT> input)
 {
  foreach (INPUT item in input)
  {
   yield return _internalStep.Process(item);
  }

  //等價於下述代碼段
  //return from INPUT item in input
  //  select _internalStep.Process(item);
 }
}

然後,定義一個支持上述類型的功能組裝的擴展方法,示例代碼如下所示:

public static class PipelineStepLoopExtensions
{
 public static IEnumerable<OUTPUT> Step<INPUT, OUTPUT>(this IEnumerable<INPUT> input, IPipelineStep<INPUT, OUTPUT> step)
 {
  LoopStep<INPUT, OUTPUT> loopDecorator = new LoopStep<INPUT, OUTPUT>(step);
  return loopDecorator.Process(input);
 }
}

最後,上層調用如下所示:

class Program
{
 static void Main(string[] args)
 {
  var list = Enumerable.Range(0, 10);
  foreach (var item in list.Step(new DoubleStep()))
  {
   Console.WriteLine(item);
  }
 }
}

總結

通過上述 5 部分示例代碼的不斷改進,最終我們實現了一個支持依賴注入和條件式組裝的管道,瞭解瞭如何進行管道式編程。掌握管道式編程可以讓我們對整個項目的架構和代碼質量都有很大幫助,感興趣的朋友可以自行查閱相關資料進行深入研究。

相關參考

好了,以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對神馬文庫的支持。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章