Answer: Objects that can be traversed by foreach must be collection or array objects, which are of the type that implements the superinterface IEnumerator or the declared GetEnumerator method Q: But when I usually use foreach in, I use it directly, and there is no problem. May I ask, why is this? If you want to implement the type of the super interface IEnumerator or the declared GetEnumerator method as asked in the question, what should you do? Thank you Answer: When using foreach in, we usually use a system-defined collection class (implementing the ICollection interface). For example, arrayList, stringDictionary, array, etc. These are packaged by the platform and are close to implementing the IEnumerator interface. In order for the class you write to be able to foreach at the same time, you must implement the interface when writing the class. This allows for foreach traversal afterwards. For example, define a class of people and implement the IEnumerator interface. If there is an array People[] tempPeople, then you can use: foreach( p in tempPeople){ console.writeline(p.name); This eliminates the trouble of using for loops. As for how to implement the Iemumerator interface. Just check MSDN. You can also look for a thicker book.
|