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;
        }
    }
}

   

 结果:

 

转载于:https://www.cnblogs.com/mileres/p/7484400.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值