简体   繁体   中英

Code confusion - why does one work, but not the other?

Note: This already works fine, but I'm trying to understand Why it works this way, but not the other.

I have a WinForm (C#) with dynamically put images, like so: 在此输入图像描述

Now if you click the 'Napred' button, these images should be deleted (among other things), for which I originally used:

foreach(Control ctrl in Controls)
    if(ctrl is PictureBox) ctrl.Dispose();

or

for(int i = 0; i < Controls.Count; i++)
    if(Controls[i] is PictureBox) Controls[i].Dispose();

Now if I run this, I get:

在此输入图像描述

But if I just change the for statement to send it backwards, it works ?

for(int i = Controls.Count - 1; i >= 0; i--)
    if(Controls[i] is PictureBox) Controls[i].Dispose();

(I'm not going to upload another image, but it deletes all of the elements (I only get the buttons left in the end))

Can someone enlighten me why one works , but not the other ?

EDIT: I'm using VS2015 community edition on Windows 10 if it's a debugging error(?)

You're trying to change the list you're iterating over, which of course will change the indexes of this list so what was at index 1 is now at index 0.

By removing from the end of the array (Ie in your reverse), the previous indexes will always be the same.

Its also important to note as stated in Matthew Watson's comment:

Control.Dispose() is special and will remove the control from a parent container's Controls list.

This isn't default behavour by most Dispose methods so therefore you won't always find this behaviour when using Dispose

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM