關於迭代器中IEnumerable與IEnumerator的區別

来源:http://www.cnblogs.com/JsonZhangAA/archive/2016/04/09/5372292.html
-Advertisement-
Play Games

首先是IEnumerable與IEnumerator的定義: 1.IEnumerable介面允許使用foreach迴圈,包含GetEnumerator()方法,可以迭代集合中的項。 2.IEnumerator介面是一個真正的集合訪問器,它包含MoveNext()方法和Current屬性,在forea ...


首先是IEnumerable與IEnumerator的定義:

1.IEnumerable介面允許使用foreach迴圈,包含GetEnumerator()方法,可以迭代集合中的項。

2.IEnumerator介面是一個真正的集合訪問器,它包含MoveNext()方法和Current屬性,在foreach迴圈中,如果MoveNext()返回True,則就是用IEnumerator介面的Current屬性來獲取對象的一個引用,用於foreach迴圈。

3.如果要迭代一個類,可以使用GetEnumerator(),其返回類型是IEnumerator.

 如果要迭代一個類成員,則用IEnumerable.

下麵的例子是迭代Person類中的類成員Ages,使用了IEnumerable。第二個例子則是迭代一個類,所以使用了IEnumerator作為返回值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace _10_5_5
{
    public class person
    {
        private string name;
        private int age;
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }
        public int Age
        {
            get
            {
                return age;
            }
            set
            {
                age = value;
            }
        }
        public person(string PName, int PAge)
        {
            Name = PName;
            Age = PAge;
        }
        public static bool operator >(person a, person b)
        {
            if (a.Age > b.Age)
                return true;
            else
                return false;
        }
        public static bool operator <(person a, person b)
        {
            if (a.Age > b.Age)
                return false;
            else
                return true;
        }
        public static bool operator >=(person a, person b)
        {
            if (a.Age >= b.Age)
            {
                return true;
            }
            else
                return false;
        }
        public static bool operator <=(person a, person b)
        {
            if (a.Age <= b.Age)
                return true;
            else
                return false;
        }
    }
    public class People : DictionaryBase
    {
        public IEnumerable Ages//註意是IEnumerable
        {
            get
            {
                foreach (object person in Dictionary.Values)
                {
                    yield return (person as person).Age;
                }
            }
        }
        public person[] GetOldest()
        {
            People oldPeople = new People();
            person oldPerson = null;
            person currentPerson;
            foreach (DictionaryEntry myPeople in Dictionary)
            {
                currentPerson = myPeople.Value as person;
                if (oldPerson == null)
                {
                    oldPerson = currentPerson;
                    oldPeople.Add(oldPerson);
                }
                else
                {
                    if (currentPerson > oldPerson)
                    {
                        oldPeople.Clear();
                        oldPeople.Add(currentPerson);
                        oldPerson = currentPerson;
                    }
                    else
                    {
                        if (currentPerson >= oldPerson)
                        {
                            oldPeople.Add(currentPerson);
                        }
                    }
                }
            }
            person[] oldestPeopleArray = new person[oldPeople.Count];
            int copyIndex = 0;
            foreach (DictionaryEntry p in oldPeople)
            {
                oldestPeopleArray[copyIndex] = p.Value as person;
                copyIndex++;
            }
            return oldestPeopleArray;
        }
        public void Add(person p)
        {
            Dictionary.Add(p.Name, p);
        }
        public person this[string SName]
        {
            get
            {
                return (person)Dictionary[SName];
            }
            set
            {
                Dictionary[SName] = value;
            }
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            person a = new person("Jack", 11);
            person b = new person("Json", 10);
            People s = new People();
            s.Add(a);
            s.Add(b);
            foreach(int age in s.Ages)
            {
                Console.WriteLine("{0}\t", age);
            }
            Console.ReadKey();
        }
    }
}

 

下麵是自定義的一個迭代器的例子:

Primer.CS

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ch11Ex03_Exam
{
    public class Primes
    {
        private long min;
        private long max;
        public Primes():this(2,100)
        {
            
        }
        public Primes(long minNum,long maxNum)
        {
            if(minNum<2)
            {
                min=2;
            }else{
                min = minNum;
            }
            max = maxNum;
        }
        public IEnumerator GetEnumerator()//返回的是IEnumerator
        {
            for(long i=min;i<max;i++)
            {
                int flag = 1;
                for(long j=2;j<Math.Sqrt(min);j++)
                {
                    if(i%j==0)
                    {
                        flag = 0;
                        break;
                    }
                }
                if(flag==1)
                {
                    yield return i;
                }
            }
        }
    }
}

Program.CS:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ch11Ex03_Exam
{
    class Program
    {
        static void Main(string[] args)
        {
            Primes s = new Primes(2, 100);
            foreach(long i in s)
            {
                Console.WriteLine("{0}\t", i);
            }
            Console.ReadKey();
        }
    }
}

 


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

-Advertisement-
Play Games
更多相關文章
  • asp.net MVC請求過程 ASP.NET MVC框架只是給開發者提供了開發web應用程式的一種選擇,並不是要取代Webform這兩種技術各有優缺點,開發者需要根據實際情況,選擇對應的技術有時候,可以在同一個項目中混合使用這兩種技術 WebForm請求過程 個人網站:http://www.51p ...
  • SqlBulkCopy原理是採用了SQL Server的BCP協議進行數據的批量複製,結合使用事務,就我們的案例而言,大約每批800條是平衡點,性能比逐條插入提高了100多倍,並前面同樣使用事務批量插入的案例性能提升了7倍以上。 個人網站:http://www.51pansou.com .net視頻 ...
  • 剛剛接觸NHibernate和FluentNHibernate,所以最好的方法是從一個簡單的例子入手。 開發環境考慮到是實際情況還有好多朋友沒有用VS2015,就用VS2013withUpdate5吧。 1.創建Asp.net Web應用程式(MVC),叫FluentNHibernateDemo1 ...
  • 分類:Unity、C#、VS2015 創建日期:2016-04-10 一、簡介 Unity擁有功能完善的地形編輯器,支持以筆刷繪製的方式實時雕刻出山脈、峽谷、平原、高地等地形。Unity地形編輯器同時提供了實時繪製地表材質紋理、樹木種植、大面枳草地佈置等功能。值得—提的是,Unity中的地形編輯器支... ...
  • 軟體下載: http://hovertree.com/h/bjaf/hwqtjwjs.htm 截圖:使用方法:點擊按鈕,選擇文件夾,就可以顯示文件夾中包含的文件總數。這個項目包含在HoverTree解決方案中。源碼下載:http://hovertree.com/h/bjaf/cao15h74.htm ...
  • 一、引言 在前一篇文章中,我向大家介紹瞭如何實現實現端對端聊天的功能的,在這一篇文章中將像大家如何使用SignalR實現群聊這樣的功能。 二、實現思路 要想實現群聊的功能,首先我們需要創建一個房間,然後每個線上用戶可以加入這個房間裡面進行群聊,我們可以為房間設置一個唯一的名字來作為標識。那Signa ...
  • 1.前言 現在這個項目已經有階段性的模塊完成了,所以就想著對這些模塊進行單元測試,以保證項目的代碼的質量。首先雖然標題是mvc+webapi實質上我只是對mvc進行的測試。用的時候vs的unit test generator.至於它的安裝和介紹在這不做詳細介紹。好的現在開始總結我的單元測試總結。 2 ...
  • 前言當我們訪問某個網站的時候需要檢測用戶是否已經登錄(通過Session是否為null),我們知道在WebForm中可以定義一個BasePage類讓他繼承System.Web.UI.Page,重寫它的OnInit()方法,在OnInit()中判斷Session中是否有用戶登錄的信息。 在mvc下該怎 ...
一周排行
    -Advertisement-
    Play Games
  • GoF之工廠模式 @目錄GoF之工廠模式每博一文案1. 簡單說明“23種設計模式”1.2 介紹工廠模式的三種形態1.3 簡單工廠模式(靜態工廠模式)1.3.1 簡單工廠模式的優缺點:1.4 工廠方法模式1.4.1 工廠方法模式的優缺點:1.5 抽象工廠模式1.6 抽象工廠模式的優缺點:2. 總結:3 ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 本章將和大家分享ES的數據同步方案和ES集群相關知識。廢話不多說,下麵我們直接進入主題。 一、ES數據同步 1、數據同步問題 Elasticsearch中的酒店數據來自於mysql資料庫,因此mysql數據發生改變時,Elasticsearch也必須跟著改變,這個就是Elasticsearch與my ...
  • 引言 在我們之前的文章中介紹過使用Bogus生成模擬測試數據,今天來講解一下功能更加強大自動生成測試數據的工具的庫"AutoFixture"。 什麼是AutoFixture? AutoFixture 是一個針對 .NET 的開源庫,旨在最大程度地減少單元測試中的“安排(Arrange)”階段,以提高 ...
  • 經過前面幾個部分學習,相信學過的同學已經能夠掌握 .NET Emit 這種中間語言,並能使得它來編寫一些應用,以提高程式的性能。隨著 IL 指令篇的結束,本系列也已經接近尾聲,在這接近結束的最後,會提供幾個可供直接使用的示例,以供大伙分析或使用在項目中。 ...
  • 當從不同來源導入Excel數據時,可能存在重覆的記錄。為了確保數據的準確性,通常需要刪除這些重覆的行。手動查找並刪除可能會非常耗費時間,而通過編程腳本則可以實現在短時間內處理大量數據。本文將提供一個使用C# 快速查找並刪除Excel重覆項的免費解決方案。 以下是實現步驟: 1. 首先安裝免費.NET ...
  • C++ 異常處理 C++ 異常處理機制允許程式在運行時處理錯誤或意外情況。它提供了捕獲和處理錯誤的一種結構化方式,使程式更加健壯和可靠。 異常處理的基本概念: 異常: 程式在運行時發生的錯誤或意外情況。 拋出異常: 使用 throw 關鍵字將異常傳遞給調用堆棧。 捕獲異常: 使用 try-catch ...
  • 優秀且經驗豐富的Java開發人員的特征之一是對API的廣泛瞭解,包括JDK和第三方庫。 我花了很多時間來學習API,尤其是在閱讀了Effective Java 3rd Edition之後 ,Joshua Bloch建議在Java 3rd Edition中使用現有的API進行開發,而不是為常見的東西編 ...
  • 框架 · 使用laravel框架,原因:tp的框架路由和orm沒有laravel好用 · 使用強制路由,方便介面多時,分多版本,分文件夾等操作 介面 · 介面開發註意欄位類型,欄位是int,查詢成功失敗都要返回int(對接java等強類型語言方便) · 查詢介面用GET、其他用POST 代碼 · 所 ...
  • 正文 下午找企業的人去鎮上做貸後。 車上聽同事跟那個司機對罵,火星子都快出來了。司機跟那同事更熟一些,連我在內一共就三個人,同事那一手指桑罵槐給我都聽愣了。司機也是老社會人了,馬上聽出來了,為那個無辜的企業經辦人辯護,實際上是為自己辯護。 “這個事情你不能怪企業。”“但他們總不能讓銀行的人全權負責, ...