责任链方式编写管道
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TestPipeline { public class Testcs { public delegate void LineDelegate(int id); private static readonly IList<Func<LineDelegate, LineDelegate>> _items = new List<Func<LineDelegate, LineDelegate>>(); /// <summary> /// /// </summary> /// <param name="line">第一个 LineDelegate 是下一个,返回的当前生成的LineDelegate</param> public void Append(Func<LineDelegate, LineDelegate> line) { _items.Add(line); } public LineDelegate Build() { LineDelegate ending = (id) => { Console.WriteLine("默认的接收编号是:" + id); }; foreach (var item in _items.Reverse()) { ending = item(ending); } return ending; } public void Run() { Append((next) => { return id => { Console.WriteLine("权限校验 开始"); next(2); Console.WriteLine("权限校验 结束"); Console.WriteLine("【权限校验】接收的编号是:" + id); }; }); Append((next) => { return id => { Console.WriteLine("页面校验 开始"); next(3); Console.WriteLine("页面校验 结束"); Console.WriteLine("【页面校验】接收的编号是:" + id); }; }); Build()(1); } /// <summary> /// 最原始的方式 实现Run 和 Build /// </summary> public void Run2() { Func<LineDelegate, LineDelegate> lineFuc1 = (next) => { return id => { Console.WriteLine("权限校验 开始"); next(2); Console.WriteLine("权限校验 结束"); Console.WriteLine("【权限校验】接收的编号是:" + id); }; }; Func<LineDelegate, LineDelegate> lineFuc2 = (next) => { return id => { Console.WriteLine("页面校验 开始"); next(3); Console.WriteLine("页面校验 结束"); Console.WriteLine("【页面校验】接收的编号是:" + id); }; }; LineDelegate ending = (id) => { Console.WriteLine("默认的接收编号是:" + id); }; //传入 最后一个,返回第二个中间件委托 var mid = lineFuc2(ending); //传入 第二个 返回第一步 var start = lineFuc1(mid); start(1); } } }