Does Class need to implement IEnumerable to use Foreach

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

    foreach does not require IEnumerable, contrary to popular belief. All it requires is a method GetEnumerator that returns any object that has the method MoveNext and the get-property Current with the appropriate signatures.

    /EDIT: In your case, however, you're out of luck. You can trivially wrap your object, however, to make it enumerable:

    class EnumerableWrapper {
        private readonly TheObjectType obj;
    
        public EnumerableWrapper(TheObjectType obj) {
            this.obj = obj;
        }
    
        public IEnumerator GetEnumerator() {
            return obj.TheMethodReturningTheIEnumerator();
        }
    }
    
    // Called like this:
    
    foreach (var xyz in new EnumerableWrapper(yourObj))
        …;
    

    /EDIT: The following method, proposed by several people, does not work if the method returns an IEnumerator:

    foreach (var yz in yourObj.MethodA())
        …;
    

提交回复
热议问题