1. ienumerable and ienumerator are not required
As we all know, the objects after foreach should inherit ienumerable. When the program is running, the essence is to call the getenumerator function of ienumerable to return an ienumerator object. foreach is to use the current of the ienumerator object, the movenext and reset members can enumerate a piece of data, but this is not required. For example, the following code:
Class fakeienumerable { Public fakeienumerator getenumerator () { Return new fakeienumerator (New Double [] {1, 34.3,-43, double. Nan, 0.0043 }); } } Class fakeienumerator { Double [] STRs; Int curidx =-1; Public fakeienumerator (double [] data) { STRs = data; } Public Double Current { Get { If (curidx <0 | curidx> = STRs. length) Throw new invalidoperationexception (); Return STRs [curidx]; } } Public bool movenext () { Return ++ curidx <STRs. length; } Public void reset () { Curidx =-1; } } Class Program { Static void main () { Foreach (VAR item in new fakeienumerable ()) Console. writeline ("type: {0} value: {1}", item. GetType (), item. tostring ()); } } |
Both the above two classes fakeienumerable and fakeienumerator do not inherit the ienumerable and ienumerator, but have the member information with the same name as ienumerable and ienumerator. The code is compiled and run successfully.
Output
Type: system. Double value: 1 Type: system. Double: 34.3 Type: system. Double value:-43 Type: system. Double value: Nan Type: system. Double: 0.0043 |
But why? You can refer to the answer below to this question. It cannot be better:
Http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/64f3dbe3-5a1a-4a70-904a-792e26376dad
2. Support ienumerator that inherits idisposable
The iterator that inherits the idisposable will be correctly processed (the dispose method is called) after foreach ends. In addition, this is not only for the real iterator (the class that inherits the ienumerator ), even the pseudo iterator class fakeienumerator mentioned above is equally treated.
Change the above fakeienumerator class code
Class fakeienumerator: idisposable { Void idisposable. Dispose () { Console. writeline ("Call dispose "); } /* The subsequent code is the same as above ...*/ } |
Running result
Type: system. Double value: 1 Type: system. Double: 34.3 Type: system. Double value:-43 Type: system. Double value: Nan Type: system. Double: 0.0043 Call dispose |
Http://www.cnblogs.com/mgen/archive/2011/07/01/2095960.html