C # IEnumerable Interface

Q: A collection of useful, and very simple, but I do not understand why the array, ArrayList and Hasttable these collections can be used directly foreach to traverse it? I think I defined a set of classes, how to do it?
Answer: This is a good question, if you view ArrayList and Hasttable definitions can see, they have achieved
with
Interface, which is the key to use the foreach.
Look through the array:
 
 
So if our custom class, can not be the same as the array to traverse it?
Let's try:
 
 
 
Operating results error:
 
 
Traversal principle: To use foreach on a custom collection classes to traverse, the need to achieve IEnmuerable interface.
(1) Because IEnmuerable enumerator interface has a return loop through a collection IEnumerator
 
 
 
(2) an enumerator IEnumerator interface
 
When using foreach, IEnumerator enumerator will be compiled into the following code to achieve the function lookup data (to the outside world is foreach syntax)
 
 
 
 
Specific implementation:
(1) adding a class DepartMent
Then let the class inherits IEnumerator interface
(2) to position the cursor in the
, And then press the alt + shift + F10, select
Select the first item
 
 
(3) This will
 
(4) into this
 
(5) so that the class can iterate with foreach.
 
 
 
 
Here's look at another interface in System.Colliction namespace: ICollection. He inherits from IEnumerable.
 

Guess you like

Origin www.cnblogs.com/schangxiang/p/11229474.html