C#實現(xiàn)遞歸調(diào)用的Lambda表達式
前段時間,我寫一個樹的訪問算法的時候,用了Visitor模式把訪問的算法分離了出來,當時打算用lambda表達式寫visit算法的,卻發(fā)現(xiàn)帶遞歸調(diào)用的lambda表達式?jīng)]想象的那么好寫,憋了半天愣是沒寫出來,由于當時趕進度,就寫成了普通的函數(shù)了。
今天晚上研究了一下遞歸調(diào)用的Lambda表達式的寫法,發(fā)現(xiàn)也還是比較簡單的,就是腦袋要轉(zhuǎn)個彎(可能當時這個彎沒有轉(zhuǎn)過來),首先給一個簡單的示例:
int i = 1; RecursiveRun(self => { Console.WriteLine("hello world " + i++); self(); }); static void RecursiveRun(Action<Action> action) { action(() => RecursiveRun(action)); }
可能有人說函數(shù)RecursiveRun是無參數(shù)的,基本上沒什么用,下面這個就是帶一個參數(shù)的版本了(如果需要更多的參數(shù)的版本,直接把RecursiveRun函數(shù)稍稍修改即可):
static void RecursiveRun<T>(T obj, Action<T, Action<T>> action) { action(obj, o => RecursiveRun(o, action)); }
通過這個函數(shù),就可以把二叉樹的遍歷算法用lambda表達式給表示出來了:
class BinTree { public int Value { get; set; } public BinTree Left { get; set; } public BinTree Right { get; set; } public BinTree(int value) { this.Value = value; } public void Accept(Action<BinTree> visitor) { visitor(this); } public void Accept(Action<BinTree, Action<BinTree>> visitor) { visitor(this, node => node.Accept(visitor)); } public override string ToString() { return Value.ToString(); } } var nodes = Enumerable.Range(0, 5).Select(i => new BinTree(i)).ToArray(); nodes[0].Left = nodes[1]; nodes[0].Right = nodes[2]; nodes[1].Left = nodes[3]; nodes[1].Right = nodes[4]; nodes[0].Accept((node, visitor) => { Console.WriteLine(node.Value); if (node.Left != null) visitor(node.Left); if (node.Right != null) visitor(node.Right); });
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#函數(shù)式程序設(shè)計之用閉包封裝數(shù)據(jù)的實現(xiàn)代碼
如果一個程序設(shè)計語言能夠用高階函數(shù)解決問題,則意味著數(shù)據(jù)作用域問題已十分突出。當函數(shù)可以當成參數(shù)和返回值在函數(shù)之間進行傳遞時,編譯器利用閉包擴展變量的作用域,以保證隨時能得到所需要的數(shù)據(jù)2014-03-03C# 使用PictureBox實現(xiàn)圖片按鈕控件的示例步驟
這篇文章主要介紹了C# 使用PictureBox實現(xiàn)圖片按鈕控件的示例步驟,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下2021-02-02DirectoryEntry配置IIS7出現(xiàn)ADSI Error:未知錯誤(0x80005000)
這篇文章主要介紹了DirectoryEntry配置IIS7出現(xiàn)ADSI Error:未知錯誤(0x80005000)的解決辦法2015-09-09