关于foreach和代表的问题 [英] Question about foreach and delegates

查看:124
本文介绍了关于foreach和代表的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设以下代码:

foreach(Item i on ItemCollection)
{
   Something s = new Something();
   s.EventX += delegate { ProcessItem(i); };
   SomethingCollection.Add(s);
}

当然,这是错误的,因为所有代表都指向相同的项目。另一种方法是:

Of course, this is wrong because all the delegates points to the same Item. The alternative is:

foreach(Item i on ItemCollection)
{
   Item tmpItem = i;
   Something s = new Something();
   s.EventX += delegate { ProcessItem(tmpItem); };
   SomethingCollection.Add(s);
}

在这种情况下,所有代表都指向自己的项目。

In this case all the delegates point to their own Item.

这种方法怎么办?还有其他更好的解决方案?

What about this approach? There is any other better solution?

推荐答案

更新:这里有很多分析和评论:

UPDATE: There is extensive analysis and commentary on this issue here:

http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/

这是一个经常报道的问题;通常它被报告为编译器错误,但实际上编译器根据规范做正确的事情。匿名函数关闭变量,而不是,并且只有一个foreach循环变量。因此,每个lambda关闭相同的变量,因此获取该变量的当前值。

This is an extremely frequently reported issue; usually it is reported as a compiler bug, but in fact the compiler is doing the right thing according to the specification. Anonymous functions close over variables, not values, and there is only a single foreach loop variable. Therefore each lambda closes over the same variable, and therefore gets the current value of that variable.

几乎每个人都是惊讶的,并导致了很多混乱和许多错误报告。考虑到改变C#的假设未来版本的规范和实现,我们是,以便在循环结构中逻辑地声明循环变量,每次通过循环给出一个新鲜变量。

This is surprising to almost everyone, and leads to much confusion and many bug reports. We are considering changing the specification and implementation for a hypothetical future version of C# so that the loop variable is logically declared inside the looping construct, giving a "fresh" variable every time through the loop.

这将是一个突破性的变化,但我怀疑依赖这种奇怪行为的人数相当低。如果您对此主题有意见,请随时向上述更新中提到的博文添加评论。谢谢!

This would be a breaking change, but I suspect the number of people who depend on this strange behaviour is quite low. If you have opinions on this subject, feel free to add comments to the blog posts mentioned up the update above. Thanks!

这篇关于关于foreach和代表的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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