Is IEnumerable required to use a foreach loop? [duplicate]

筅森魡賤 提交于 2020-01-11 04:23:08

问题


I was wondering, when exactly can I use the foreach loop? Do I have to implement IEnumerable?


回答1:


There is no need to implement the IEnumerable interface to use the foreach statement. Here is a quote from the MSDN (http://msdn.microsoft.com/en-us/library/9yb8xew9.aspx):

In C#, it is not absolutely necessary for a collection class to inherit from IEnumerable and IEnumerator in order to be compatible with foreach. As long as the class has the required GetEnumerator, MoveNext, Reset, and Current members, it will work with foreach. Omitting the interfaces has the advantage of enabling you to define the return type of Current to be more specific than Object, which provides type-safety.




回答2:


You can foreach though any object that implements IEnumerable or IEnumberable<T>




回答3:


Comprehensive explanation: http://msdn.microsoft.com/en-us/library/aa664754%28VS.71%29.aspx




回答4:


Ask yourself - do you really need a loop counter

The rule of thumb I use is determining if I am moving data between two indexed containers, where I really do need an index value to address the destination, or more generally, 'do I need an index count for each item I am processing in the loop' ? In those cases, I use a for loop, in pretty much all other cases (where foreach can deal with the container, which as noted above is pretty much every container) - the reason is pretty simple, it looks pretty stupid to use foreach and then have to go to the trouble of manually maintaining a loop counter.



来源:https://stackoverflow.com/questions/3584351/is-ienumerable-required-to-use-a-foreach-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!