我们都知道数组(int[])和列表(List)都可以进行foreach,如果想自定义类实现foreach必须实现IEnumerable接口。
通过字面的意思可以知道:
IEnumerable 可迭代的,可以说是一个声明式的接口,但没有具体如何实现迭代器(iterator),仅有可返回IEnumerator 类型的方法
IEnumerator 迭代器,通过实现该接口就可以作为一个迭代器(iterator),包含了具体的需要实现的方法
一个类型是否支持foreach遍历,必须满足下面两个条件:
1、这个类实现IEnumerable接口
2、这个类有一个public的GetEnumerator的实例方法,并且返回类型中(IEnumerator)具有public 的bool MoveNext()方法和public的Current属性
public interface IEnumerable
{
[DispId(-4)]
IEnumerator GetEnumerator();
}
public interface IEnumerator
{
object Current { get; }
bool MoveNext();
void Reset();
}using UnityEngine;
using System.Collections;
using System;
public class Test1 : MonoBehaviour
{
void Start ()
{
Init();
}
void Init()
{
Person[] peopleArray = new Person[3];
peopleArray[0] = new Person("John","Smith");
peopleArray[1] = new Person("Jim", "Johnson");
peopleArray[2] = new Person("Sue", "Rabon");
People peopleList = new People(peopleArray);
foreach(Person p in peopleList)
{
Debug.Log(p.FirstName + "," + p.LastName);
}
}
}
public class Person
{
public string FirstName = "";
public string LastName = "";
public Person(string firstName,string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
}
public class People : IEnumerable
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length];
for(int i=0;i