在foreach循环中更新集合 [英] update collection in foreach loop

查看:173
本文介绍了在foreach循环中更新集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

IEnumerable<string> imagesFileNames = FindImages(imagesFolder);
 foreach(string imageFileName in imagesFileNames)
            {
                //my code
                //IEnumerable<string> imagesFilesNames = FindImages(imagesFolder);
                // it doesn't work!!  
            }




我有这样的代码.我可以在foreach循环中更新IENumerable集合吗?


谢谢,


Dcan.




I have a code like this. Can i update the IENumerable collection in foreach loop?


Thanks,


Dcan.

推荐答案

那真是个坏主意.您不能在枚举过程中更改集合.如果更改集合本身,则会将枚举器置于未知状态,从而使枚举器失效,从而无法预测行为.如果您尝试这样做,.NET Framework通常将引发异常.

根据您发布的简短代码片段,您没有理由在foreach循环中调用已经枚举文件名集合的FindImages.
That''s a really bad idea. You cannot change a collection in the middle of enumerating it. If you alter the collection itself you''ll put the enumerator into an unknown state, thus invalidating it to the point where behavior cannot be predicted. The .NET Framework will usually throw an exception if you try this.

Based on the brief code snippet you posted, there is no reason for you to be calling FindImages inside the foreach loop that is already enumerating a collection of filenames.


请参阅我对问题的评论:您没有解释什么是无效";而且您也没有解释您尝试达到的目标.但是,我希望,有一点便笺能使您理解这种怪异情况下的一切:您已经定义了两个完全不同的变量,这些变量指向完全不同且不相关的对象:on是循环前的imageFileNames,另一个是循环内的,定义了一个每个周期中都有新对象.

您需要做的只是考虑一下.

—SA
Please see my comment to the question: you did not explain what''s "not working"; and you did not explain what did you try to achieve. However, I hope, lust one note should make you understand everything in this weird situation: you have defined two completely different variables pointing to completely different and unrelated objects: on is imageFileNames before the loop, and another one inside loop, defining a new object in each cycle.

All you need to do is to think about it.

—SA


这篇关于在foreach循环中更新集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆