关于foreach和delegate的问题

Question about foreach and delegates(关于foreach和delegate的问题)
本文介绍了关于foreach和delegate的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设如下代码:

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

当然,这是错误的,因为所有的代表都指向同一个 Item.替代方案是:

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/closure-over-the-loop-variable-considered-harmful-part-one/

这是一个非常频繁报告的问题;通常它被报告为编译器错误,但实际上编译器正在按照规范做正确的事情.匿名函数关闭 variables,而不是 values,并且只有一个 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和delegate的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)