When to use which for?

前端 未结 7 927
慢半拍i
慢半拍i 2021-01-05 14:48

EDIT Additional options and a slightly extended question below.

Consider this contrived and abstract example of a class body. It demonstrates four different w

7条回答
  •  北荒
    北荒 (楼主)
    2021-01-05 15:04

    Generally I go with what logically matches what I'm doing. If I'm looping over the entire list all use foreach but if I'm looping through a subset I use a for loop. Also, if you are modifying the collection in your loop you have to use a for loop.

    The only other option that I'm aware that hasn't already been stated is to manually do what foreach is doing, which is useful if you need to maintain the state of the enumerator outside of the scope in which its created.

    using(var myEnum = aList.GetEnumerator()){
        while(myEnum.MoveNext()){
            myEnum.Current.SomeAction();
        }
    }
    

提交回复
热议问题