C#--IEnumerable 與 IEnumerator 的區別


一、 IEnumerator 

         解釋:它是一個的集合訪問器,使用foreach語句遍歷集合或數組時,就是調用 Current、MoveNext()的結果。

// 定義如下
public interface IEnumerator { // 返回結果: 集合中的當前元素。 object Current { get; } // 返回結果: 如果枚舉數成功地推進到下一個元素,則為 true;如果枚舉數越過集合的結尾,則為 false。 bool MoveNext(); // 調用結果:將枚舉數設置為其初始位置,該位置位於集合中第一個元素之前。 void Reset(); }

 

二、IEnumerable

        解釋:它利用 GetEnumerator() 返回 IEnumerator 集合訪問器。

 // 定義如下
        public interface IEnumerable
        {
            // 返回結果: 可用於循環訪問集合的IEnumerator 對象。
            IEnumerator GetEnumerator();
        }

 

三、舉個栗子   

using System;
using System.Collections;
using System.Collections.Generic;

namespace ArrayListToList
{
    // 定義student類
    public class Student
    {
        public string Id { get; set; }

        public string Name { get; set; }

        public string Remarks { get; set; }

        public Student(string id, string name, string remarks)
        {
            this.Id = id;
            this.Name = name;
            this.Remarks = remarks;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            ArrayList arrStus = new ArrayList
            {
                new Student("1313001", "liuliu"," little rabbit"),
                new Student("1313002", "zhangsan", "little tortoise")
            };
            // List<T> 繼承了IEnumerable<T>, IEnumerble<T>繼承了IEnumerable.
            List<Student> stuL = ArrListToArr<Student>(arrStus);
            foreach(Student stu in stuL)
            {
                Console.WriteLine($"{ stu.Name + "  " + stu.Id + "  " + stu.Remarks }");
            };
        }

        // arrList 轉換為 List<T>
        // ArrList 定義時已繼承了IEnumerable
        static List<T> ArrListToArr<T>(ArrayList arrL)
        {
            List<T> list = new List<T>();
            
            IEnumerator enumerator = arrL.GetEnumerator();
            
            while (enumerator.MoveNext())
            {
                 T item = (T)(enumerator.Current);
                 list.Add(item);
            }
           
            return list;
        }
    }
}

   

 結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM