C#中的foreach和yield

来源:http://www.cnblogs.com/ldyblogs/archive/2017/09/28/foreach.html
-Advertisement-
Play Games

1. foreach C#編譯器會把foreach語句轉換為IEnumerable介面的方法和屬性。 foreach語句會解析為下麵的代碼段。 調用GetEnumerator()方法,獲得數組的一個枚舉 在while迴圈中,只要MoveNext()返回true,就一直迴圈下去 用Current屬性訪 ...


1. foreach

C#編譯器會把foreach語句轉換為IEnumerable介面的方法和屬性。

foreach (Person p in persons)
 {
     Console.WriteLine(p);
 }

foreach語句會解析為下麵的代碼段。

調用GetEnumerator()方法,獲得數組的一個枚舉

在while迴圈中,只要MoveNext()返回true,就一直迴圈下去

用Current屬性訪問數組中的元素

IEnumerator enumerator = persons. GetEnumerator();
 while (enumerator.MoveNext())
 {
    Person p = (Person) enumerator.Current;
    Console.WriteLine(p);
}

2. yield語句

yield語句的兩種形式:

yield return <expression>;
yield break;

使用一個yield return語句返回集合的一個元素

包含yield語句的方法或屬性是迭代器。迭代器必須滿足以下要求

a. 返回類型必須是IEnumerableIEnumerable<T>IEnumeratorIEnumerator<T>

b. 它不能有任何ref或out參數

yield return語句不能位於try-catch快。yield return語句可以位於try-finally的try塊

try
              {
                  // ERROR: Cannot yield a value in the boday of a try block with a catch clause
                 yield return "test";
              }
             catch
             { }
 
              try
             {
                 // 
                 yield return "test again";
             }
             finally
             { }
 
             try
             { }
             finally
             { 
                 // ERROR: Cannot yield in the body of a finally clause
                yield return ""; 
             }

yield break語句可以位於try塊或catch塊,但是不能位於finally塊

下麵的例子是用yield return語句實現一個簡單集合的代碼,以及用foreach語句迭代集合

using System;
using System.Collections.Generic;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            HelloCollection helloCollection = new HelloCollection();
            foreach (string s in helloCollection)
            {
                Console.WriteLine(s);
                Console.ReadLine();
            }
        }
    }

    public class HelloCollection
    {
        
        public IEnumerator<String> GetEnumerator()
        {
            // yield return語句返回集合的一個元素,並移動到下一個元素上;yield break可以停止迭代
            yield return "Hello";
            yield return "World";
        }
    }
}

使用yield return語句實現以不同方式迭代集合的類:

using System;
using System.Collections.Generic;

namespace ConsoleApplication8
{
    class Program
    {
        static void Main(string[] args)
        {
            MusicTitles titles = new MusicTitles();
            foreach (string title in titles)
            {
                Console.WriteLine(title);
            }
            Console.WriteLine();

            foreach (string title in titles.Reverse())
            {
                Console.WriteLine(title);
            }
            Console.WriteLine();

            foreach (string title in titles.Subset(2, 2))
            {
                Console.WriteLine(title);
                Console.ReadLine();
            }
        }
    }

    public class MusicTitles
    {
        string[] names = { "a", "b", "c", "d" };
        public IEnumerator<string> GetEnumerator()
        {
            for (int i = 0; i < 4; i++)
            {
                yield return names[i];
            }
        }

        public IEnumerable<string> Reverse()
        {
            for (int i = 3; i >= 0; i--)
            {
                yield return names[i];
            }
        }

        public IEnumerable<string> Subset(int index, int length)
        {
            for (int i = index; i < index + length; i++)
            {
                yield return names[i];
            }
        }
    }
}

以上動圖由“圖鬥羅”提供


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在應用程式獲取視頻數據的流程中,都是通過 ioctl 命令與驅動程式進行交互,常見的 ioctl 命令有: 1 VIDIOC_QUERYCAP /* 獲取設備支持的操作 */ 2 VIDIOC_G_FMT /* 獲取設置支持的視頻格式 */ 3 VIDIOC_S_FMT /* 設置捕獲視頻的格式 * ...
  • 設置密碼 設置時間 註意大小寫 顯示文件類型 查看文件 查看歷史命令記錄 獲取幫助 pinfo 查看textinfo's GNU文檔系統 ...
  • shell shell命令分為兩種:分別是內部命令和外部命令。 Linux中,預設的shell是bash 系統中的shell 控制台的名詞: 標準Linux命令: bash組合鍵: ...
  • windows 7安裝 準備 1、iso系統鏡像文件(我一般選用純凈版) 2、Windows7-USB-DVD-Download-Tool-Installer-en-US(啟動盤製作) 3、準備4G以上空U盤,之後的過程中會被格式化,不要放重要文件 4、C盤(系統盤)留有8G以上空間 5、備份網卡驅 ...
  • ...
  • 轉載需註明來源:http://www.cnblogs.com/yczcc/p/7594322.html openssl官網:https://www.openssl.org 下載源碼 源碼地址為:https://www.openssl.org/source/old/;當前最新版本為 1.1.0f,ht ...
  • 創建LVM分區: 相關命令: pvcreat /dev/sdb{1,2,3} 創建物理捲 vgcreat test_vg1 /dev/sdb1 創建捲組 vgcreat test_vg2 -s 16M /dev/sdb2 /dev/sdb3 指定PE大小為16M lvcreat 在已存在的捲組中創建 ...
  • 自己挖了一個大坑,,,然後苦逼的在碼代碼重寫樣式! 廢物不多少 直接上代碼 先在前臺創建一個TextBox,然後各種附加的屬性加上去:如圖所示 效果圖: 樣式代碼: 本文原創出處:http://www.cnblogs.com/PettyHandSome/ 歡迎各位轉載,但是未經作者本人同意,轉載文章 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...