zoukankan      html  css  js  c++  java
  • 自定义集合支持使用 foreach循环访问该集合

    自定义集合支持使用 foreach循环访问该集合,需要实现 IEnumerableIEnumerator 接口。

    using System;
    using System.Collections;

    public class Person
    {
       
    public Person(string fName, string lName)
       {
          
    this.firstName = fName;
          
    this.lastName = lName;
       }

       
    public string firstName;
       
    public string lastName;
    }

    public class People : IEnumerable
    {
       
    private Person[] _people;
       
    public People(Person[] pArray)
       {
          _people 
    = new Person[pArray.Length];

          
    for (int i = 0; i < pArray.Length; i++)
          {
             _people[i] 
    = pArray[i];
          }
       }

       
    public IEnumerator GetEnumerator()
       {
          
    return new PeopleEnum(_people);
       }
    }

    public class PeopleEnum : IEnumerator
    {
       
    public Person[] _people;

       
    // Enumerators are positioned before the first element
       
    // until the first MoveNext() call.
       int position = -1;

       
    public PeopleEnum(Person[] list)
       {
          _people 
    = list;
       }

       
    public bool MoveNext()
       {
          position
    ++;
          
    return (position < _people.Length);
       }

       
    public void Reset()
       {
          position 
    = -1;
       }

       
    public object Current
       {
          
    get
          {
             
    try
             {
                
    return _people[position];
             }
             
    catch (IndexOutOfRangeException)
             {
                
    throw new InvalidOperationException();
             }
          }
       }
    }

    class Example
    {
       
    public static void Demo(System.Windows.Controls.TextBlock outputBlock)
       {
          Person[] peopleArray 
    = new Person[3]
            {
                
    new Person("John""Smith"),
                
    new Person("Jim""Johnson"),
                
    new Person("Sue""Rabon"),
            };

          People peopleList 
    = new People(peopleArray);
          
    foreach (Person p in peopleList)
             outputBlock.Text 
    += p.firstName + " " + p.lastName + " ";

       }
    }

    /* This code produces output similar to the following:
     * 
     * John Smith
     * Jim Johnson
     * Sue Rabon
     * 
     
    */

    作者:freshman1987
    出处:http://www.cnblogs.comfreshman1987/
    本文版权归作者所有,欢迎转载,但未经作者同意不能转载,否则保留追究法律责任的权利。
  • 相关阅读:
    程序中转站
    数据结构与算法题!(总索引)
    C语言常用函数-isdigit()判断字符是否为十进制数字函数
    C语言常用函数-iscntrl()判断字符是否为控制字符函数
    C语言常用函数-isalpha()判断字符是否为英文字母函数
    C语言常用函数-isalnum()判断字符是否为字母或数字函数
    C语言常用函数-isascii()判断字符是否为ASCII码函数
    NX二次开发-在NX状态区显示一行文本UF_UI_set_status
    NX二次开发-UFUN在NX提示区显示一行文本UF_UI_set_prompt
    NX二次开发-调NX的dxfdwg.exe转换器导出dxf,dwg
  • 原文地址:https://www.cnblogs.com/freshman1987/p/3747567.html
Copyright © 2011-2022 走看看