使用IEnumerable接口遍历数据,这在项目中会常常的用到,这个类型呢主要是一个枚举器。数组
1.首先须要让该类型实现一个名字叫IEnumerable的接口,实现该接口的主要目的是为了让当前类型中增长一个名字叫GetEnumerator()的方法。this
public class Person : IEnumerable { private string[] Friends = new string[] { "张三", "李四", "王五", "赵六" }; public string Name { get; set; } public int Age { get; set; } public string Email { get; set; } #region IEnumerable 成员 //这个方法的做用就是返回一个“枚举器” public IEnumerator GetEnumerator() { return new PersonEnumerator(this.Friends); } #endregion }
2.但愿一个类型被枚举遍历,就是要实现一个枚举器方法spa
public class PersonEnumerator : IEnumerator { public PersonEnumerator(string[] fs) { _friends = fs; } private string[] _friends; //通常下标都是一开始指向了第一条的前一条。第一条是0 private int index = -1; #region IEnumerator 成员 public object Current { get { if (index >= 0 && index < _friends.Length) //下标有范围 { return _friends[index]; } else { throw new IndexOutOfRangeException(); } } } public bool MoveNext() { if (index + 1 < _friends.Length) //下标有范围 { index++; return true; } return false; } public void Reset() { index = -1; } #endregion }
3.而后进行遍历,这里呢能够调用本身封装的MoveNext方法去找数组元素code
Person p = new Person(); IEnumerator etor = p.GetEnumerator(); while (etor.MoveNext()) { Console.WriteLine(etor.Current.ToString()); }
也能够直接使用foreach,并且主要是由于是枚举元素,相似与数组,list等等之类的,均可以使用Lambda表达式来进行数据的处理blog
Person p = new Person(); foreach (string item in p) { Console.WriteLine(item); } Console.WriteLine("ok");
4.输出的结果以下:接口