Class是否需要实现IEnumerable才能使用Foreach

Bri*_*n G 15 c# ienumerable foreach

这是在C#中,我有一个类,我从其他人的DLL使用.它没有实现IEnumerable,但有两个传递IEnumerator的方法.有没有办法可以在这些上使用foreach循环.我正在使用的课程是密封的.

Kon*_*lph 15

foreach没有要求IEnumerable,出乎人们意料.它需要的是一个方法GetEnumerator,它返回具有该方法的任何对象MoveNextCurrent具有适当签名的get-property .

/编辑:但是,在你的情况下,你运气不好.但是,您可以简单地包装您的对象,以使其可枚举:

class EnumerableWrapper {
    private readonly TheObjectType obj;

    public EnumerableWrapper(TheObjectType obj) {
        this.obj = obj;
    }

    public IEnumerator<YourType> GetEnumerator() {
        return obj.TheMethodReturningTheIEnumerator();
    }
}

// Called like this:

foreach (var xyz in new EnumerableWrapper(yourObj))
    …;
Run Code Online (Sandbox Code Playgroud)

/编辑:下面的方法,由几个人提出的,并没有如果该方法返回一个工作IEnumerator:

foreach (var yz in yourObj.MethodA())
    …;
Run Code Online (Sandbox Code Playgroud)


Tor*_*ing 7

Re:如果foreach不需要显式接口契约,它是否使用反射找到GetEnumerator?

(我不能评论,因为我没有足够高的声誉.)

如果你暗示运行时反射,那么没有.它完成所有编译时间,另一个鲜为人知的事实是它还检查可能实现IEnumerator 的返回对象是否是一次性的.

要查看此操作,请考虑此(可运行)代码段.


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

namespace ConsoleApplication3
{
    class FakeIterator
    {
        int _count;

        public FakeIterator(int count)
        {
            _count = count;
        }
        public string Current { get { return "Hello World!"; } }
        public bool MoveNext()
        {
            if(_count-- > 0)
                return true;
            return false;
        }
    }

    class FakeCollection
    {
        public FakeIterator GetEnumerator() { return new FakeIterator(3); }
    }

    class Program
    {
        static void Main(string[] args)
        {
            foreach (string value in new FakeCollection())
                Console.WriteLine(value);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Ada*_*hes 6

根据MSDN:

foreach (type identifier in expression) statement
Run Code Online (Sandbox Code Playgroud)

表达式是:

对象集合或数组表达式.集合元素的类型必须可转换为标识符类型.不要使用计算结果为null的表达式.计算实现IEnumerable的类型或声明GetEnumerator方法的类型.在后一种情况下,GetEnumerator应返回实现IEnumerator的类型或声明IEnumerator中定义的所有方法.