Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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))
- …;
- foreach (var yz in yourObj.MethodA())
- …;
- 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);
- }
- }
- }
- foreach (type identifier in expression) statement
- class ForeachWrapper
- {
- private IEnumerator _enumerator;
- public ForeachWrapper(Func<IEnumerator> enumerator)
- {
- _enumerator = enumerator;
- }
- public IEnumerator GetEnumerator()
- {
- return _enumerator();
- }
- }
- foreach (var element in new ForeachWrapper(x => myClass.MyEnumerator()))
- {
- ...
- }
- class Counter
- {
- public IEnumerable<int> Count(int max)
- {
- int i = 0;
- while (i <= max)
- {
- yield return i;
- i++;
- }
- yield break;
- }
- }
- Counter cnt = new Counter();
- foreach (var i in cnt.Count(6))
- {
- Console.WriteLine(i);
- }
- class EnumerableAdapter
- {
- ExternalSillyClass _target;
- public EnumerableAdapter(ExternalSillyClass target)
- {
- _target = target;
- }
- public IEnumerable GetEnumerator(){ return _target.SomeMethodThatGivesAnEnumerator(); }
- }
- foreach (object y in X.A())
- {
- //...
- }
- // or
- foreach (object y in X.B())
- {
- //...
- }
- public class Foo
- {
- private int[] _someInts = { 1, 2, 3, 4, 5, 6 };
- public IEnumerator GetEnumerator()
- {
- foreach (var item in _someInts)
- {
- yield return item;
- }
- }
- }
- public IEnumerator GetEnumerator()
- {
- return _someInts.GetEnumerator();
- }
- foreach (int item in new Foo())
- {
- Console.Write("{0,2}",item);
- }
Add Comment
Please, Sign In to add comment