Some experiences about Foreach

xiaoxiao2021-04-09  535

Using foreach constraints 1 using foreach must be implemented in the foreach in object class (inherited Ienumerable). 2Foreach statement is a package of enumeration, which only allows writing to be written from the collection. 3Foreach inside, does not allow the collection of the Foreach in object to be allowed.

problem

ArrayList arr = new arraylist (); arr.add ("123"); arr.add ("456"); arr.add ("789"); foreach (string str in arr) {Arr.Remove ("789" Console.writeline (STR);}

The above code will cause the InvalidOperationException exception when the second object in ArrayList is convenient.

Analysis When using foreach, first call the getENUMERATOR method of the traversed object, return an enumerator, and Foreach will traverse the number of enumerated enumerations. Personally feel that the actual operation of Foreach is: IEnumerator enumarr = arr.geeteumerator (); while (enumarr.movenext ()) {set.remove ("789"); system.console.writeline (EnumarrR.current);} and MSDN There is the following description: "As long as the collection remains unchanged, the number will remain valid. If the collection changes (for example, adding, modifying or deleting elements), the number will be invalid and cannot be restored, and the next time The call to MoveNext or Reset will raise InvalidOperationException. "So the code in the above question has occurred."

转载请注明原文地址:https://www.9cbs.com/read-133158.html

New Post(0)