我看书上说,只有实现了IEnumerable接口的类才能使用foreach,为什么下面的情况,没有继承IEnumerable也可以啊。using System;
using System.Collections;namespace Array
{
    public class HelloCollection //: IEnumerable (这里写不写都行)
    {
        public IEnumerator GetEnumerator()
        {
            yield return "hello";
            yield return "world";
        }
    }    public class Test
    {
        static void Main()
        {
            HelloCollection hc = new HelloCollection();
            foreach (string str in hc)
            {
                Console.WriteLine(str);
            }
        }
    }
}

解决方案 »

  1.   

    参考这个帖子...
    http://topic.csdn.net/u/20090508/09/26e63539-ada5-4808-9c9b-2fe7e53f3409.html从来没有“只有实现了IEnumerable接口的类才能使用foreach”的说法...你看的书是垃圾,可以扔掉了...
      

  2.   

    你这个迭代跟书上说的不是一个概念
    书上说的是Hello对象,HelloCollection 实现Hello对象的迭代
    也就是说 foreach(Hello h in hc)的情况是需要实现IEnumerable的
      

  3.   

    IEnumberable 不是必须的,但IEnuberator是必须的。其实,你已经实现了呀
      

  4.   

    GetEnumerator方法用yield语句创建了一个枚举器类型。
      

  5.   

           public IEnumerator GetEnumerator() 
            { 
                yield return "hello"; 
                yield return "world"; 
            } 
    事实上,这个在底层应该是从对象中动态调用方法。参考后期绑定。有点类似这个,是用反射来的。认的是"GetEnumerator",而不是接口。但是多半是在没有找到接口时才会去尝试反射调用吧。要不.net不可能有这么高的效率。
      

  6.   

    thank you.在 C# 中,集合类不一定要从 IEnumerable 和 IEnumerator 继承以便与 foreach 兼容。只要此类具有必需的 GetEnumerator、MoveNext、Reset 和 Current() 成员,就可 foreach 与一起使用。省略接口有一个好处:您可以将 Current 的返回类型定义得比 Object 更为明确,从而提供类型安全。