日期:2014-05-18  浏览次数:20801 次

C#中迭代集合的不同方式

 

请看下面的例子,类MusicTitles可以用默认方式通过GetEnumerator()方法迭代标题

,用Reverse()方法逆序迭代标题,用Subset()方法迭代子集

---------类定义--------------

    public class MusicTitles
    {
        string[] names = new string[] {
            "china","country","food","think"
        };

        public IEnumerator<string> GetEnumerator()
        //该方法是类的默认迭代,注意方法名一定要为GetEnumerator()
        //类支持的默认迭代式定义为返回IEnumerator的GetEnumerator()方法
        {
            for (int i = 0; i < 4; i++)
            //返回所有数组内容
            {
                yield return names[i];
            }
        }

        public IEnumerable<string> Reverse()
        //返回数组的倒序
        {
            for (int i = 3; i >= 0; i--)
            {
                yield return names[i];
            }
        }

        public IEnumerable<string> Subset(int Start,int Length)
        //返回数组的一部分,Start:开始索引,Length:从开始索引处取多少个元素
        {
            for (int i = Start; i < Start + Length; i++)
            {
                yield return names[i];
            }
        }
    }

-----------测试代码------------

        private void button1_Click(object sender, EventArgs e)
        {
            string ResultMsg = "";
            MusicTitles musics = new MusicTitles();
            ResultMsg += "---GetEnumerator()\r\n";
            foreach (var o in musics)
            {
                ResultMsg += o.ToString() + "\r\n";
            }
            ResultMsg += "---Reverse()\r\n";
      &n