c# foreach枚举器

时间:2023-03-09 17:34:11
c# foreach枚举器

要是自己的类支持foreach ,必须在类中必须有GetEnumerator方法,该方法返回的是一个IEnumerator类型的枚举器;

public class MyStruct
{
public string[] sName = new string[] { "张三", "李四", "王五" };
public IEnumerator GetEnumerator()
{
return new MyStructEnumerator(sName);
}
}

  所以自己得写一个类类继承IEnumerator接口,并在类中实现IEnumerator接口;

public class MyStructEnumerator : IEnumerator
{
//要遍历的对象
private string[] sList;
public MyStructEnumerator(string[] get)
{
sList = get; //得到
}
    //索引
private int index = -1;
//获取当前项
public object Current
{
get
{
if(index>=0&&index<sList.Length)
{
return sList[index];
}
else
{
throw new IndexOutOfRangeException();
}
}
}
//移到下一个
public bool MoveNext()
{
if (index+1 < sList.Length)
{
index++;
return true;
}
else
{
return false;
}
}
     //重置
public void Reset()
{ index = -1;
}
}

  然后在实例化自己写的MyStruct就可以用foreach来遍历了;

或者更方便的办法,只需在MyStrcu中添加一个方法;(方法一)

public class MyStruct
{
public string[] sName = new string[] { "张三", "李四", "王五" }; //当返回值类型是IEnumerator时,编译器会自动帮我们生成一个“枚举类”,即实现了IEnumerator的接口的类
public IEnumerable GetObj()
{
for(int i=0;i<sName.Length;i++)
{
yield return sName[i];
}
}
}

  然后可以直接调用foreach(string res in MyStruct.GetObj){...};

也可以(方法2)

public class MyStruct
{
public string[] sName = new string[] { "张三", "李四", "王五" };
public IEnumerator GetEnumerator()
{
for(int i=0;i<sName.Length;i++)
{
yield return sName[i];
}
}
}

  之后直接调用foreach(string res in MyStruct);比上面的写法看起来方便在不用再去调用GetObj方法;

方法一和方法二的区别是一个要调用方法, 方法二不用调用方法是因为类里有GetEnumerator方法,foreach会认出这个方法,而方法一没有,所以要。出方法,方法一会自动去实现IEnumerable接口.