Debugging a foreach loop in C#: what iteration is this?
Other than setting a debug variable and incrementing it every time you start the foreach, when you break in with the Visual Studio debugger connected, is there a way to tell that this is the Xth time through the loop?
I guess this would be a feature of Visual Studio if anything, not something that would be added to the compiled code.
Heres a previous Stack Overflow question that seems to be what your looking for: get-index-of-current-foreach-iteration
Answer quoted from that link:
Foreach is for iterating over collections that implement IEnumerable. It does this by calling GetEnumerator on the collection, which will return an Enumerator.
This Enumerator has a method and a property:
Current returns the object that Enumerator is currently on, MoveNext updates Current to the next object.
Obviously, the concept of an index is foreign to the concept of enumeration, and cannot be done.
Because of that, most collections are able to be traversed using an indexer and the for loop construct.
I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.
Set a breakpoint inside the loop, then right click on the breakpoint to set the conditions. You can also right click to see the hit count while debugging and reset it if you want. You can set a boolean expression that is evaluated when the breakpoint hits to conditionally break (or just pass over).
Expanding on Garo Yeriazarian's answer...
A quick and dirty way without recompiling. Example code:
var ints = new[] {5, 6, 0, 1};
foreach (var i in ints)
{
Debug.WriteLine(100 / i);
}
Add one breakpoint before the loop and one inside it. When the first is hit and you want to start counting, set a Hit Count condition:
Set some large hit count condition and reset the counter and continue. Then when the exception or whatever fires, you can check the "Current hit count" again.
链接地址: http://www.djcxy.com/p/52976.html上一篇: 在'foreach'循环中获取数组键