C# 迭代器模式

实现一个自定义类型,支持迭代:

把peopel看成是List或person[]


 class people:IEnumerable
    {
        private readonly Person[] persons;
        public people(Person[] ps)
        {
            persons=new Person[ps.Length];
            for (var i = 0; i < ps.Length; i++)
            {
                persons[i] = ps[i];
            }
               
        }


        public IEnumerator GetEnumerator()
        {
            return new PeopleEnumerator(persons);
        }
    }


  class Person
    {
        
        public long Id { get; set; }
      
        public string Name { get; set; }

        public int Age { get; set; }

        public string Sex { get; set; }
      
    }


  class PeopleEnumerator : IEnumerator
    {
        private int position = -1;
        Person[] persons;
        public object Current
        {
            get { return persons[position]; }
        }
        public PeopleEnumerator( Person[] _persons)
        {
            persons = _persons;
        }

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

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



  

//测试一下:
static void Main(string[] args) { Person p1 = new Person() { Name = "1" }; Person p2 = new Person() { Name = "2" }; people peopleList = new people(new Person[] { p1, p2 }); foreach (var per in peopleList) { Console.WriteLine((per as Person).Name); } //等价与下面代码 IEnumerator enumerator = peopleList.GetEnumerator(); while (enumerator.MoveNext()) { Person p = enumerator.Current as Person; Console.WriteLine(p.Name); } Console.ReadKey(); }
 
  

 

用yield代替上面那么多代码实现迭代:
  class people : IEnumerable
    {
        private readonly Person[] persons;
        public people(Person[] ps)
        {
            persons = new Person[ps.Length];
            for (var i = 0; i < ps.Length; i++)
            {
                persons[i] = ps[i];
            }

        }


        public IEnumerator GetEnumerator()
        {
            for (int i = 0; i < persons.Length; i++)
            {
                yield return persons[i];
            }
        }
    }
 
  

 





你可能感兴趣的:(C# 迭代器模式)