通过IEnumerable接口遍历数据
使用IEnumerable接口遍历数据,这在项目中会经常的用到,这个类型呢主要是一个枚举器。
1.首先需要让该类型实现一个名字叫IEnumerable的接口,实现该接口的主要目的是为了让当前类型中增加一个名字叫GetEnumerator()的方法。
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.希望一个类型被枚举遍历,就是要实现一个枚举器方法
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方法去找数组元素
Person p = new Person();
IEnumerator etor = p.GetEnumerator();
while (etor.MoveNext())
{
Console.WriteLine(etor.Current.ToString());
}
也可以直接使用foreach,而且主要是因为是枚举元素,类似与数组,list等等之类的,都可以使用Lambda表达式来进行数据的处理
Person p = new Person();
foreach (string item in p)
{
Console.WriteLine(item);
}
Console.WriteLine("ok");
4.输出的结果如下:

转 https://www.cnblogs.com/yinxuejunfeng/p/9747972.html

浙公网安备 33010602011771号