代码改变世界

C# 通过接口IEnumerator让自己编写的对象/类,实现foreach遍历方法

2012-06-20 13:26  Andrew.Wangxu  阅读(718)  评论(0编辑  收藏  举报

简单说明:

    要想自己写的类实现foreach方法,那么可以继承IEnumerator来实现。

除了实现继承接口中的方法,还要实现一个GetEnumerator()方法才行,返回值是你要遍历的对象。  如Item~ (我这里是返回Students)

直接上代码上图吧:

using System;
using System.Collections.Generic;
using System.Text;

namespace IEnumeratorDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Students stu = new Students();
            stu.Add("andrew");
            stu.Add("jeack");
            stu.Add("knna");

            foreach (var item in stu)
            {
                Console.WriteLine(item);
            }

            Console.ReadLine();
        }
    }
}

 

以上是Main方法的调用代码。

下面是Students的代码:

using System;
using System.Collections.Generic;
using System.Text;

namespace IEnumeratorDemo
{
    public class Students:IEnumerator<string>
    {
        //存储所有的学生名字,如: “andrew;knna;jaeck”
        string studentNameList = string.Empty;

        //存储遍历时的Current变量
        private string current;

        //存储实现MoveNext()遍历的下标
        private int index;

        //新增学生名称
        public void Add(string studentName)
        {
            studentNameList += studentName + ";";
        }

        //构造函数
        public Students() { }
        public Students(string studentNameList)
        {
            this.studentNameList = studentNameList;
        }
        
        //执行foreach时,会调用该方法
        public Students GetEnumerator()
        {
            return new Students(this.studentNameList);
        }

        //获取当前遍历的值
        public string Current
        {
            get { return current; }
        }

        public void Dispose()
        {
            //throw new NotImplementedException();
        }

        //获取当前遍历的对象
        object System.Collections.IEnumerator.Current
        {
            get { return current; }
        }

        //每次遍历都会执行的方法
        public bool MoveNext()
        {
            string[] strArray = studentNameList.Split(';');
            if (strArray.Length > index)
            {
                current = strArray[index];
                index++;
                return true;
            }
            else
            {
                return false;
            }
        }

        public void Reset()
        {
            throw new NotImplementedException();
        }
    }
}

 

完整项目例子下载:https://files.cnblogs.com/andrew-blog/IEnumeratorDemo.rar

参考:http://www.wxzzz.com/?id=105