zoukankan      html  css  js  c++  java
  • 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;
            }
        }
    }

       

     结果:

  • 相关阅读:
    WordPress WooCommerce ‘hide-wc-extensions-message’参数跨站脚本漏洞
    WordPress WP-Realty插件‘listing_id’参数SQL注入漏洞
    WordPress Videowall插件‘page_id’参数跨站脚本漏洞
    MySQL备忘点(上)
    Print工具类
    用于图片缩放的工具类
    重载、重写、方法相同
    Try-Catch-Finally代码块中的return
    Fltiss项目的架构、包名的定义和类的划分
    优化版快速排序
  • 原文地址:https://www.cnblogs.com/mileres/p/7484400.html
Copyright © 2011-2022 走看看