Does Class need to implement IEnumerable to use Foreach

前端 未结 11 1786
慢半拍i
慢半拍i 2020-12-09 11:04

This is in C#, I have a class that I am using from some else\'s DLL. It does not implement IEnumerable but has 2 methods that pass back a IEnumerator. Is there a way I can u

11条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 11:20

    For a class to be usable with foeach all it needs to do is have a public method that returns and IEnumerator named GetEnumerator(), that's it:

    Take the following class, it doesn't implement IEnumerable or IEnumerator :

    public class Foo
    {
        private int[] _someInts = { 1, 2, 3, 4, 5, 6 };
        public IEnumerator GetEnumerator()
        {
            foreach (var item in _someInts)
            {
                yield return item;
            }
        }
    }
    

    alternatively the GetEnumerator() method could be written:

        public IEnumerator GetEnumerator()
        {
            return _someInts.GetEnumerator();
        }
    

    When used in a foreach ( Note that the no wrapper is used, just a class instance ):

        foreach (int item in new Foo())
        {
            Console.Write("{0,2}",item);
        }
    

    prints:

    1 2 3 4 5 6

提交回复
热议问题