Foreach 循環中的Lambda 表達式失敗
考慮以下初始化委託列表的程式碼,每個委託都呼叫具有特定類型和問候語的SayGreetingToType 方法:
<code class="csharp">public class MyClass { public delegate string PrintHelloType(string greeting); public void Execute() { Type[] types = new Type[] { typeof(string), typeof(float), typeof(int) }; List<printhellotype> helloMethods = new List<printhellotype>(); foreach (var type in types) { // Initialize the lambda expression with the captured variable 'type' var sayHello = new PrintHelloType(greeting => SayGreetingToType(type, greeting)); helloMethods.Add(sayHello); } // Call the delegates with the greeting "Hi" foreach (var helloMethod in helloMethods) { Console.WriteLine(helloMethod("Hi")); } } public string SayGreetingToType(Type type, string greetingText) { return greetingText + " " + type.Name; } }</printhellotype></printhellotype></code>
執行此程式碼後,您會期望看到:
Hi String Hi Single Hi Int32
但是,由於閉包行為,類型數組中的最後一個類型Int32 被所有lambda 捕獲表達式。因此,所有委託都以相同的類型呼叫SayGreetingToType,導致意外輸出:
Hi Int32 Hi Int32 Hi Int32
解決方案
要解決此問題,我們需要捕獲lambda 表達式中循環變數的值而不是變數本身:
<code class="csharp">public class MyClass { public delegate string PrintHelloType(string greeting); public void Execute() { Type[] types = new Type[] { typeof(string), typeof(float), typeof(int) }; List<printhellotype> helloMethods = new List<printhellotype>(); foreach (var type in types) { // Capture a copy of the current 'type' value using a new variable var newType = type; // Initialize the lambda expression with the new variable 'newType' var sayHello = new PrintHelloType(greeting => SayGreetingToType(newType, greeting)); helloMethods.Add(sayHello); } // Call the delegates with the greeting "Hi" foreach (var helloMethod in helloMethods) { Console.WriteLine(helloMethod("Hi")); } } public string SayGreetingToType(Type type, string greetingText) { return greetingText + " " + type.Name; } }</printhellotype></printhellotype></code>
此修改可確保每個lambda 表達式都有自己的類型副本,從而允許它使用正確的值呼叫SayGreetingToType輸入參數。
以上是為什麼 Foreach 迴圈內的 Lambda 表達式會捕捉循環變數的最後一個值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本文解釋了C標準模板庫(STL),重點關注其核心組件:容器,迭代器,算法和函子。 它詳細介紹了這些如何交互以啟用通用編程,提高代碼效率和可讀性t

本文詳細介紹了c中有效的STL算法用法。 它強調了數據結構選擇(向量與列表),算法複雜性分析(例如,std :: sort vs. std vs. std :: partial_sort),迭代器用法和並行執行。 常見的陷阱

本文詳細介紹了C中的有效異常處理,涵蓋了嘗試,捕捉和投擲機制。 它強調了諸如RAII之類的最佳實踐,避免了不必要的捕獲塊,並為強大的代碼登錄例外。 該文章還解決了Perf

文章討論了在C中有效使用RVALUE參考,以進行移動語義,完美的轉發和資源管理,重點介紹最佳實踐和性能改進。(159個字符)

C 20範圍通過表現力,合成性和效率增強數據操作。它們簡化了複雜的轉換並集成到現有代碼庫中,以提高性能和可維護性。

本文討論了使用C中的移動語義來通過避免不必要的複制來提高性能。它涵蓋了使用std :: Move的實施移動構造函數和任務運算符,並確定了關鍵方案和陷阱以有效

本文討論了C中的動態調度,其性能成本和優化策略。它突出了動態調度會影響性能並將其與靜態調度進行比較的場景,強調性能和之間的權衡

C語言數據結構:樹和圖的數據表示與操作樹是一個層次結構的數據結構由節點組成,每個節點包含一個數據元素和指向其子節點的指針二叉樹是一種特殊類型的樹,其中每個節點最多有兩個子節點數據表示structTreeNode{intdata;structTreeNode*left;structTreeNode*right;};操作創建樹遍歷樹(先序、中序、後序)搜索樹插入節點刪除節點圖是一個集合的數據結構,其中的元素是頂點,它們通過邊連接在一起邊可以是帶權或無權的數據表示鄰


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Dreamweaver CS6
視覺化網頁開發工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

記事本++7.3.1
好用且免費的程式碼編輯器

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中