Does Class need to implement IEnumerable to use Foreach

前端 未结 11 1782
慢半拍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:33

    Re: If foreach doesn't require an explicit interface contract, does it find GetEnumerator using reflection?

    (I can't comment since I don't have a high enough reputation.)

    If you're implying runtime reflection then no. It does it all compiletime, another lesser known fact is that it also check to see if the returned object that might Implement IEnumerator is disposable.

    To see this in action consider this (runnable) snippet.

    
    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);
            }
        }
    }
    

提交回复
热议问题