咱們知道在ASP.NET MVC中,在Action方法上應用ActionFilter過濾法時,它的執行流程以下圖:ide
這個功能看起來很通常麼,但是實現功能的代碼吊炸天(嘿嘿,要班門弄斧了,大神繞行吧!),卡忙北鼻...spa
因爲在ASP.NET MVC中其功能涉及的代碼太多,看起來太亂,下面就經過一個例子重點來介紹下這段吊爆的代碼!3d
例子的環境是這樣的:code
一、有這麼一個接口IFilterFunction,其中定義了兩個方法!blog
public interface IFilterFunction { void Before(); void After(); }
二、一個方法!接口
public string ActionMethed() { Console.WriteLine("Action方法內容"); return "Action"; }
需求來了,爲了在執行ActionMethod方法的先後進行一些操做,要求實現功能:先執行全部實現了IFilterFunction接口的全部類的Before方法,再執行ActionMethed方法,而後再執行全部實現了IFilterFunction接口的全部類的After方法!(目的是在執行ActionMethod方法的先後進行一些操做)get
對於這麼一個需求,首先想到能夠這麼實現:源碼
小吊實現:string
public class FilterOne : IFilterFunction { public void Before() { Console.WriteLine("執行FilterOne的Before方法"); } public void After() { Console.WriteLine("執行FilterOne的After方法"); } } public class FilterTwo : IFilterFunction { public void Before() { Console.WriteLine("執行FilterTwo的Before方法"); } public void After() { Console.WriteLine("執行FilterTwo的BAfter方法"); } } public class FilterThree : IFilterFunction { public void Before() { Console.WriteLine("執行FilterThree的Before方法"); } public void After() { Console.WriteLine("執行FilterThree的After方法"); } }
public string Start() { FilterOne filterOne = new FilterOne(); FilterTwo filterTwo = new FilterTwo(); FilterThree filterThree = new FilterThree(); filterThree.Before(); filterTwo.Before(); filterOne.Before(); string str = ActionMethed(); filterOne.After(); filterTwo.After(); filterThree.After(); return str; }
雖說能夠實現,可是這麼作有點過小兒科了,說好的吊爆呢?
來咯......it
大吊實現:
public class FilterOne : IFilterFunction { public void Before() { Console.WriteLine("執行FilterOne的Before方法"); } public void After() { Console.WriteLine("執行FilterOne的After方法"); } } public class FilterTwo : IFilterFunction { public void Before() { Console.WriteLine("執行FilterTwo的Before方法"); } public void After() { Console.WriteLine("執行FilterTwo的BAfter方法"); } } public class FilterThree : IFilterFunction { public void Before() { Console.WriteLine("執行FilterThree的Before方法"); } public void After() { Console.WriteLine("執行FilterThree的After方法"); } }
public string Start() { Func<string> continuation = () => ActionMethed(); List<IFilterFunction> lists = new List<IFilterFunction>(); lists.Add(new FilterOne()); lists.Add(new FilterTwo()); lists.Add(new FilterThree()); //就是它 Func<string> p = lists.Aggregate(continuation, (newcontinuation, filter) => () => Do(newcontinuation, filter)); return p(); } public string Do(Func<string> continuation, IFilterFunction filter) { filter.Before(); string str = continuation(); filter.After(); return str; }
執行結果爲:
沒錯,就是這麼牛逼,利用累加器來一層一層的包裝委託,以後執行委託,再一層一層的去執行。其過程如圖:
ASP.NET MVC也就是使用這種方式來完成對Action方法和ActionFilter過濾器的執行。即:利用累加器來包裝委託!
朋友,你能寫出這樣的代碼嗎? 實例源碼下載