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<YourType> 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())
…;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…