• 自定义集合支持使用 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/
    本文版权归作者所有,欢迎转载,但未经作者同意不能转载,否则保留追究法律责任的权利。
  • 相关阅读:
    程序运行bug查看
    c# webbrowser 的html调用js出错
    c# dll使用注意
    支持ie的时间控件 html
    sql 条件插入
    软件自动更新原理
    c# 数组不能直接=,需要clone
    打包成exe程序
    逆袭大学
    Heritage from father
  • 原文地址:https://www.cnblogs.com/freshman1987/p/3747567.html
Copyright © 2020-2023  润新知