This article is a mirror article of machine translation, please click here to jump to the original article.

View: 17820|Reply: 0

[Source] The type of interface or method that can be traversed with foreach needs to be implemented.

[Copy link]
Posted on 9/26/2015 10:37:46 AM | | |
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.





Previous:Interview algorithm questions 1, 1, 2, 3, 5, 8, 13, 21, 34...... find out what the 30th digit is, and use a recursive algorithm to find out
Next:What is the origin of the dark clouds that broke out of Ctrip and other leaks?
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com