C# IEnumerable和IEnumerator的區別,如何?

來源:互聯網
上載者:User

IEnumerable介面和IEnumerator介面是.NET中非常重要的介面,二者有何區別?

    1. 簡單來說IEnumerable是一個聲明式的介面,聲明實現該介面的類就是“可迭代的enumerable”,但並沒用說明如何?迭代器(iterator).其代碼實現為:

         public interface IEnumerable
         {
                IEnumerator GetEnumerator();
          }
    2. 而IEnumerator介面是實現式介面,它聲明實現該介面的類就可以作為一個迭代器iterator.其代碼實現為:

        public interface IEnumerator
       {
                object Current { get; }

                bool MoveNext();
                void Reset();
        }

   3.一個collection要支援Foreach進行遍曆,就必須實現IEnumerable,並一某種方式返回迭代器對象:IEnumerator.

   那麼又如何?這兩個介面呢? 其代碼如下:

  假設有一個Person類,其有兩個屬性FirstName和LastName

  public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Person(string firstName, string lastName)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
        }
    }

另外通過People類來實現IEnumerable和IEnumerator介面.

//實現IEnumerable介面

public class People :IEnumerable

{

   public Person [] pers;

   public People(Person [] ps)

    {

      this.pers = ps;

    }

    public IEnumerator GetEnumerator()

    {

         //foreach(Person p in pers)

         // {

             //  yield return p;

          // }

      return new People1(pers);

      }

}

  //實現IEnumerator介面

   public class People1 : IEnumerator
    {
        public Person[] pers;
        public People1(Person[] per)
        {
            this.pers = per;
        }
        int position = -1;

        public bool MoveNext()
        {
            position++;
            return position < pers.Length;
        }
        public void Reset()
        {
            position=-1;
        }
        public object Current
        {
            get
            {
               try
               {
                   return pers[position];
               }
                catch(IndexOutOfRangeException ex)
                {
                    throw new InvalidOperationException();
                }
            }
        }
    }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.