轩辕kuku
论坛版主
论坛版主
  • UID14
  • 粉丝6
  • 关注1
  • 发帖数78
  • 社区居民
  • 原创写手
阅读:440回复:0

C#开发基础——如何让你类进行foreach遍历(迭代器)

楼主#
更多 发布于:2016-05-21 13:45
unity3d开发中,经常用到协程StartCoroutine去执行另外一段代码,而这一段代码只能放到IEnumerator里面,然后通过yield语句来控制程序的运行。在C#中还可以通过IEnumerator来实现迭代器的功能。
IEnumerable和IEnumrator是实现迭代器的两个核心接口。IEnumerable是声明接口,IEnumerator是实现接口。具体事例,如何写一个类并实现迭代器

public struct PeopleInfo
{
    public string Name;
    public int Age;
    public string Address;
    public PeopleInfo(string _name, int _age, string _address)
    {
        this.Name = _name;
        this.Age = _age;
        this.Address = _address;
    }
}
 
public class People : IEnumerable
{
    public List<PeopleInfo> peopleList = new List<PeopleInfo>();
 
    public People()
    {
        peopleList.Add(new PeopleInfo("小水", 26, "北京朝阳"));
        peopleList.Add(new PeopleInfo("小士", 22, "上海徐家汇"));
        peopleList.Add(new PeopleInfo("小冠", 23, "广州番禺"));
        peopleList.Add(new PeopleInfo("小轩", 25, "深圳福田"));
        peopleList.Add(new PeopleInfo("小明", 20, "深圳福田"));
    }
 
    public PeopleInfo this[int index]
    {
        get { return peopleList[index]; }
    }
 
    public IEnumerator GetEnumerator()
    {
        return new PeopleEnum(peopleList);
    }
 
}
 
public class PeopleEnum : IEnumerator
{
    private List<PeopleInfo> M_PeopleList;
    public PeopleEnum(List<PeopleInfo> _peopleList)
    {
        M_PeopleList = _peopleList;
    }
    int position = -1;
    public bool MoveNext()
    {
        position++;
        return (position < M_PeopleList.Count);
    }
 
    public void Reset()
    {
        position = -1;
    }
 
    public object Current
    {
        get { return M_PeopleList[position]; }
    }
 
}
测试代码:
public class test : MonoBehaviour {
 
    // Use this for initialization
    void Start () {
        People people = new People();
        foreach (PeopleInfo p in people)
        {
            Debug.Log(p.Name+p.Age+p.Address);
        }
    }
     
    // Update is called once per frame
    void Update () {
     
    }
}
打印结果:

图片:QQ图片20160521133405.png





大家可以去看看IEnumerable和IEnumrator两个接口里面提供的方法:
public interface IEnumerable
{
    [DispId(-4)]
    IEnumerator GetEnumerator();
}
 
public interface IEnumerator
{
    object Current { get; }
    bool MoveNext();
    void Reset();
}
这里一部分内容其实在Unity3D的开发中用的到比较多,可以去参考Unity3D的消息系统,Message消息管理类一般都会用到迭代器。若想深入研究这一部分的内容,大家可以参考一下一下大牛的帖子,他们是完全从.Net的方向去解析:
http://blog.csdn.net/byondocean/article/details/6871881
http://www.cnblogs.com/heyuquan/archive/2012/08/15/2639475.html

最新喜欢:

kingdong020543kingdo... 归海一啸归海一啸

欢迎分享

游客

返回顶部