.NET幫助 C# Yield Return(開發者的工作原理) Jacob Mellor 更新:2025年6月22日 下載 IronPDF NuGet 下載 DLL 下載 Windows Installer 開始免費試用 LLM副本 LLM副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 C# 是由 Microsoft 開發的最受歡迎的程式語言之一,它提供了一些特性,使您的程式碼更優雅且高效。 其中一個特性是 yield 關鍵字,它首次在 C# 2.0 中引入。Microsoft 提供了 yield 關鍵字語句的完整語言參考,讓您探索如何在迭代器方法中使用它們,您可以在官方 Microsoft 文檔 yield中查看。 在本文中,我們將探討 C# 中的 yield return,研究其功能、用例以及如何改變您對迭代的處理方式。 Understanding the Basics: Iteration in C# 迭代是程式設計中的基本概念,而 C# 提供了各種機制來實現它。 傳統上,for 和 foreach 迴圈一直是迭代集合的常用工具。 然而,C# 引入了更優雅的解決方案,即在 return 語句中應用 yield 關鍵字,並通過使用 IEnumerable 介面。 yield return 語句的效率 yield return 本質上是一個用於迭代器方法的語句,提供了一種更高效的方式來生成數值序列。 它允許您創建迭代器,而無需在記憶體中生成整個集合,使其尤為適用於大型數據集或無限序列。 這是一個簡單的程式碼片段來說明 yield return 的基本用法: using System; using System.Collections.Generic; public class Example { // Method that generates numbers from start to end using 'yield return' public IEnumerable<int> GenerateNumbers(int start, int end) { // Loop from 'start' to 'end' for (int i = start; i <= end; i++) { yield return i; // Returns each number in the sequence without breaking the loop } } public static void Main() { // Usage: Using 'foreach' to iterate over numbers generated by 'GenerateNumbers' foreach (var number in new Example().GenerateNumbers(1, 5)) { Console.WriteLine(number); // Outputs numbers 1 - 5 } } } using System; using System.Collections.Generic; public class Example { // Method that generates numbers from start to end using 'yield return' public IEnumerable<int> GenerateNumbers(int start, int end) { // Loop from 'start' to 'end' for (int i = start; i <= end; i++) { yield return i; // Returns each number in the sequence without breaking the loop } } public static void Main() { // Usage: Using 'foreach' to iterate over numbers generated by 'GenerateNumbers' foreach (var number in new Example().GenerateNumbers(1, 5)) { Console.WriteLine(number); // Outputs numbers 1 - 5 } } } $vbLabelText $csharpLabel 在這個例子中,GenerateNumbers 方法使用 yield return 來生成從 start 到 end 的數字序列。 迭代器是惰性評估的,這意味著每個數字在迭代執行期間按需生成。 惰性評估與效率 yield return 語句的顯著優勢之一是它支持惰性評估的能力。 與傳統方法生成整個集合再進行迭代不同,yield return 一次生成一個值。這可能會帶來顯著的記憶體節省,尤其是在處理大型數據集時。 有狀態迭代:處理複雜情況 yield return 語句不僅限於生成簡單序列; 它在處理迭代器塊中的更複雜情況時表現優異。 通過在迭代中維持狀態機,您可以創建能夠記住序列中位置的迭代器。 using System; using System.Collections.Generic; public class FibonacciExample { // Method that generates Fibonacci numbers up to the specified count public IEnumerable<string> GenerateFibonacci(int count) { int a = 0, b = 1; for (int i = 0; i < count; i++) { yield return a.ToString(); // Returns the Fibonacci number as a string int temp = a; a = b; b = temp + b; } } public static void Main() { // Usage: Iterating over Fibonacci numbers generated by 'GenerateFibonacci' foreach (var fibNumber in new FibonacciExample().GenerateFibonacci(8)) { Console.WriteLine(fibNumber); // Outputs a Fibonacci number sequence } } } using System; using System.Collections.Generic; public class FibonacciExample { // Method that generates Fibonacci numbers up to the specified count public IEnumerable<string> GenerateFibonacci(int count) { int a = 0, b = 1; for (int i = 0; i < count; i++) { yield return a.ToString(); // Returns the Fibonacci number as a string int temp = a; a = b; b = temp + b; } } public static void Main() { // Usage: Iterating over Fibonacci numbers generated by 'GenerateFibonacci' foreach (var fibNumber in new FibonacciExample().GenerateFibonacci(8)) { Console.WriteLine(fibNumber); // Outputs a Fibonacci number sequence } } } $vbLabelText $csharpLabel 在這個例子中,GenerateFibonacci 方法使用 yield return 來創建斐波那契數列。 在迭代之間保持狀態,確保有效生成果和輸出斐波那契數字。 構建無限序列 yield return 的一個引人入勝的應用是其創建無限數值序列的能力。 由於值是即時生成的,您可以表現出無窮的序列而不需要消耗無限的記憶體。 using System; using System.Collections.Generic; public class InfiniteSequenceExample { // Method that generates an infinite sequence of even numbers public IEnumerable<int> GenerateEvenNumbers() { int num = 0; while (true) { yield return num; num += 2; } } public static void Main() { // Usage: Generating even numbers using the 'GenerateEvenNumbers' method var evenNumberIterator = new InfiniteSequenceExample().GenerateEvenNumbers().GetEnumerator(); for (int i = 0; i < 5; i++) { evenNumberIterator.MoveNext(); Console.WriteLine(evenNumberIterator.Current); // Outputs the first 5 even numbers } } } using System; using System.Collections.Generic; public class InfiniteSequenceExample { // Method that generates an infinite sequence of even numbers public IEnumerable<int> GenerateEvenNumbers() { int num = 0; while (true) { yield return num; num += 2; } } public static void Main() { // Usage: Generating even numbers using the 'GenerateEvenNumbers' method var evenNumberIterator = new InfiniteSequenceExample().GenerateEvenNumbers().GetEnumerator(); for (int i = 0; i < 5; i++) { evenNumberIterator.MoveNext(); Console.WriteLine(evenNumberIterator.Current); // Outputs the first 5 even numbers } } } $vbLabelText $csharpLabel 在這個例子中,GenerateEvenNumbers 方法創建了一個偶數數字的迭代器,您可以根據需要對其進行迭代。 您還可以使用 yield break 語句與 yield return 結合使用來停止並退出迴圈,為迴圈創建自定迭代。 IronPDF 簡介:功能強大的 C# 程式庫 IronPDF 作為一個多功能的 C# 程式庫而脫穎而出,旨在簡化處理 PDF 的複雜性。 無論您是生成發票、報告還是其他文件,IronPDF 都能為您提供在 C# 應用中無縫地將 HTML 內容轉換為精美且專業的 PDF。 安裝 IronPDF:快速啟動 要將 IronPDF 合併到您的 C# 專案中,您可以快速安裝 IronPDF NuGet 套件。 在您的套件管理器控制台中執行以下命令: Install-Package IronPdf 或者,您可以在 NuGet 套件管理器中找到 "IronPDF" 並從那裡安裝它。 使用 IronPDF 生成 PDF 使用 IronPDF 創建 PDF 是一個簡單的過程。 讓我們來看看一個基本的例子: using IronPdf; public class PdfGenerationExample { public static void Main() { var htmlContent = "<html><body><h1>Hello, IronPDF!</h1></body></html>"; // Create a new PDF renderer instance var pdfRenderer = new ChromePdfRenderer(); // Render the HTML content as a PDF and save it to a file pdfRenderer.RenderHtmlAsPdf(htmlContent).SaveAs("C:/GeneratedDocument.pdf"); } } using IronPdf; public class PdfGenerationExample { public static void Main() { var htmlContent = "<html><body><h1>Hello, IronPDF!</h1></body></html>"; // Create a new PDF renderer instance var pdfRenderer = new ChromePdfRenderer(); // Render the HTML content as a PDF and save it to a file pdfRenderer.RenderHtmlAsPdf(htmlContent).SaveAs("C:/GeneratedDocument.pdf"); } } $vbLabelText $csharpLabel 在上面的例子中,使用 IronPDF 將HTML 內容渲染為 PDF 文件,然後將其保存到指定的位置。 欲了解更多詳細訊息,請訪問 IronPDF 文件。 yield return 和 IronPDF 的交集 現在,讓我們探討 yield return 語句,一個用於惰性評估和高效迭代的強大工具,是否可以無縫整合到 IronPDF 中。 考慮一種情境,您需要使用 yield return 生成包含某一項清單的 PDF 文件。 您可以利用 yield 語句的優勢動態生成內容,然後使用 IronPDF 將該內容轉換為 PDF。 以下程式碼片段使用 yield 語句生成 PDF 文件,以控制 PDF 內容的動態變化: using System; using System.Collections.Generic; using System.Linq; using IronPdf; class Program { // Method that dynamically generates content using 'yield return' public static IEnumerable<string> GenerateDynamicContent() { yield return "Item 1"; yield return "Item 2"; yield return "Item 3"; } public static void Main(string[] args) { // Generate dynamic content using the 'GenerateDynamicContent' function var dynamicContent = GenerateDynamicContent(); // Create HTML structure for the PDF document with dynamic content var dynamicPdfContent = $@" <html> <body> <h1>List of Items</h1> <ul> {string.Join("", dynamicContent.Select(item => $"<li>{item}</li>"))} </ul> </body> </html> "; // Create a new PDF document with dynamically generated content var dynamicPdfRenderer = new ChromePdfRenderer(); dynamicPdfRenderer.RenderHtmlAsPdf(dynamicPdfContent).SaveAs("C:/DynamicItems.pdf"); } } using System; using System.Collections.Generic; using System.Linq; using IronPdf; class Program { // Method that dynamically generates content using 'yield return' public static IEnumerable<string> GenerateDynamicContent() { yield return "Item 1"; yield return "Item 2"; yield return "Item 3"; } public static void Main(string[] args) { // Generate dynamic content using the 'GenerateDynamicContent' function var dynamicContent = GenerateDynamicContent(); // Create HTML structure for the PDF document with dynamic content var dynamicPdfContent = $@" <html> <body> <h1>List of Items</h1> <ul> {string.Join("", dynamicContent.Select(item => $"<li>{item}</li>"))} </ul> </body> </html> "; // Create a new PDF document with dynamically generated content var dynamicPdfRenderer = new ChromePdfRenderer(); dynamicPdfRenderer.RenderHtmlAsPdf(dynamicPdfContent).SaveAs("C:/DynamicItems.pdf"); } } $vbLabelText $csharpLabel 在此範例中,GenerateDynamicContent 方法利用 yield return 提供動態項目的序列。 然後將生成的內容合並到 HTML 結構中,並由 IronPDF 用於創建 PDF 文件。 結論 總之,yield return 是 C# 中一個強大而優雅的特性,改變了您處理迭代的方式。 它支持惰性評估、能夠處理具有有狀態迭代的複雜情況,並創建無限序列,使其成為您程式設計工具箱中的寶貴工具。 無論您是在處理大型數據集還是實施複雜的演算法,yield return 都能讓您撰寫更高效且富有表達力的程式碼。 雖然 yield return 促進了內容的高效和按需生成,但 IronPDF 介入以無縫地將該內容轉換為專業的 PDF 文件。 不論您是動態地創建清單、報告或其他文件,這種協同作用使您能夠將您的 C# 文件生成能力提升到新的高度。 擁抱這個充滿活力的雙子星的潛力,讓您的 PDF 在動態且高效生成的內容中閃耀! IronPDF 提供免費試用,讓您像在商業模式中一樣測試其完整功能。 了解從 $799 開始的IronPDF 授權的更多訊息。 常見問題解答 如何使用 yield return 語句來增強 C# 中的迭代? 在 C# 中,可以利用 yield return 語句高效生成序列。它允許創建按需生產值的迭代器,這有助於節省記憶體,因為不需要儲存整個集合。 在處理大型數據集時,yield return 提供了哪些優勢? yield return 提供了延遲評估的優勢,這意味著僅在需要時生成值。在處理大型數據集時,這顯著降低了記憶體使用量,因為不需要將完整序列存儲在記憶體中。 yield return 可以與 C# 中的 PDF 生成結合使用嗎? 是的,yield return 可以用來動態生成內容,然後使用 IronPDF 將其轉換為 PDF 格式。這種方法促進了在 C# 應用程式內的高效和動態文檔生成。 yield return 如何簡化 C# 中無限序列的創建? yield return 通過即時生成值簡化了無限序列的創建。這意味着它可以無限期地生成值而不會耗盡記憶體,因為它僅在需要時創建每個元素。 在 C# 編程環境中,延遲評估有什麼好處? 在 C# 中,延遲評估藉由 yield return 使得值僅在迭代過程中需要時才計算。這導致更高效的記憶體使用,並在處理大量或複雜的數據序列時可以提高性能。 如何使用 C# 庫將 HTML 內容轉換為 PDF? 您可以使用 IronPDF 庫在 C# 中將 HTML 內容轉換為 PDF。庫中的 ChromePdfRenderer 可以將 HTML 和 CSS 轉換成專業級的 PDF 文件。 yield return 與 IronPDF 的實際用例是什麼? 實際用例是動態生成報告數據,然後使用 IronPDF 將這些數據轉換為 PDF。這種方法對於創建動態文檔非常有效,因為無需在記憶體中預生成所有內容。 在 C# 中使用 yield return 對開發人員有哪些主要好處? yield return 提供了多個好處,包括透過延遲評估提高記憶體效率、管理複雜的迭代方案的能力,以及生成無限序列而不會記憶體溢出的潛力。 如何安裝處理 PDF 的 C# 庫? 要在 C# 專案中安裝像 IronPDF 這樣的 PDF 操作庫,您可以使用 NuGet 套件管理器,命令如下:Install-Package IronPDF。 Jacob Mellor 立即與工程團隊聊天 首席技術官 Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。 相關文章 更新2026年2月20日 銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET Jacob Mellor 藉由 CurlDotNet 彌補了這方面的不足,CurlDotNet 是為了讓 .NET 生態系統能熟悉 cURL 而建立的函式庫。 閱讀更多 更新2025年12月20日 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新2025年12月20日 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 C# REPL(開發者的工作原理)C# 陣列排序(開發者的工...
更新2026年2月20日 銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET Jacob Mellor 藉由 CurlDotNet 彌補了這方面的不足,CurlDotNet 是為了讓 .NET 生態系統能熟悉 cURL 而建立的函式庫。 閱讀更多