zoukankan      html  css  js  c++  java
  • IEnumerable接口学习

    用途:IEnumerable 只是为了实现foreach语句用的.
    主要的方法有:IEnumerator GetEnumerator()   //返回一个循环访问集合的枚举数,返回类型是IEnumerator
    实例:
     
    public class Person : IEnumerable 
        { 
            private string[] names= new string[] { "A", "B", "C" }; 
          
             public IEnumerator GetEnumerator() 
            { 
                 //调用PersonEnumerator类的构造函数,并Person类中的names数组传递过去 
                     return new PersonEnumerator(names); 
            }  
         }
    public class PersonEnumerator : IEnumerator 
        { 
           //定义一个字符串数组 
           private string[] _names;   
          //遍历时的索引 
           private int index = -1; 
     
           //构造函数,带一个字符串数组的参数 
           public PersonEnumerator(string[] temp) 
           { 
               _names = temp; 
           } 

         //返回当前索引指向的names数组中的元素 
         public object Current 
           { 
               get { return _names[index]; } 
         } 
    //索引,判断是否遍历完成 
            public bool MoveNext() 
           { 
              index++; 
                if (index < _names.Length) 
              { 
                   return true; 
               } 
                else 
                   return false; 
         } 

         //重置索引的值,以便下一次遍历 
           public void Reset() 
           { 
               index = -1; 
          } 
        } 
    static void Main(string[] args)          {         
    Person p1 = new Person();          
    IEnumerator rator = p1.GetEnumerator();        
        while (rator.MoveNext())          
        { 
    Console.WriteLine(rator.Current);         
      }        
        Console.ReadKey();       
    }
     

    总结:继承IEnumerable 接口的, 只要实现了这个接口的对象都可以用来遍历。

     
     
  • 相关阅读:
    SystemTap----常用变量、宏、函数和技巧
    RPM制作
    percona-MYSQLGUI监控
    Rsyslog配置文件详解
    理解 Linux 网络栈(1):Linux 网络协议栈简单总结 图
    tcp-backlog配置
    Clumsy logo差网络环境模拟工具 Clumsy
    Android Studio 配置模拟器AVD存放路径(默认在c盘,解决c盘空间不够问题)
    Android Studio 导入的项目编码错误问题
    21分钟 MySQL 入门教程
  • 原文地址:https://www.cnblogs.com/aggierwyp/p/wpf_IEnumerable.html
Copyright © 2011-2022 走看看