日期:2014-05-17  浏览次数:20811 次

关于IEnumerable与IEnumerator还是不懂
本帖最后由 jxfinest 于 2013-11-08 02:37:59 编辑
using System;
using System.Collections;

namespace ConsoleApplication11
{
    class Program
    {
        public class D9TecMembers:IEnumerable //把:IEnumerable去掉貌似也可以(去不去掉无所谓,因为代码已经实现了相应的接口)。再把代码一中的GetEnumerator换任意名,就不行,而再把IEnumerator改成IEnumerable就行了,感觉IEnumerable条件更宽松,可以这样说吧?后边跟什么名称的方法都可以,但IEnumerator就不行了,跟其它的方法名就不行(会出现“System.Collections.IEnumerator”不包含“GetEnumerator”的公共定义,因此 foreach 语句不能作用于“System.Collections.IEnumerator”类型的变量),必须与GetEnumerator()相互结合(如果有public IEnumerator GetEnumerator()这行语句的话,但是去掉也不会出错),所以由此得出结论,这里的GetEnumerator()并不是普通的方法名,它与IEnumerator相配的话下边对应的代码二为foreach (string title in titles),它与IEnumerable相配的时候是任意名的性质,下边的对应的代码二为foreach (string title in titles. GetEnumerator())。有哪位高手能为我解释一下这种现象的理由吗?
        {
            string[] names = { "Wei Gao", "Zhao Zhang", "Changji Song", "Zhike Chang", "Denian Zhang", "Zhaotian Yang", "Guangyue Cai" };
            public IEnumerator GetEnumerator()//代码一
            {
                for (int i = 0; i < names.Length; i++)
                {
                    yield return names[i];//返回迭代器
                }
            }
            public IEnumerable Reverse()
            {
                for (int i = names.Length - 1; i >= 0; i--)
                {
                    yield return names[i];
                }
            }
            public IEnumerable Subset(int index, int length)
            {

                for (int i = index; i < index + length; i++)
          &nbs