本文介绍了是否有一个foreach变量的C#的重用理由吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用lambda前pressions或C#匿名方法,我们必须要警惕的的进入修改封的陷阱。例如:

 的foreach(字符串中的变种S)
{
   查询= query.Where(ⅰ= GT; i.Prop == S); //获得修改关闭
   ...
}

由于修改后的关闭,上述code将导致所有的其中,条款的查询是基于<$ C $终值ç>取值。

由于这里解释,没有性能优势声明外循环的变量,一般情况下只有我能这样做觉得原因是,如果你打算使用变量循环的范围:

 字符串s;
而(enumerator.MoveNext())
{
   S = enumerator.Current;
   ...
}
变种finalString =秒;

然而,在的foreach 循环中定义的变量不能在循环外使用:

 的foreach(字符串s中的字符串)
{
}
变种finalString =秒; //将不起作用:你的范围之内。

因此​​,编译器声明的方式,使得它非常容易,往往很难发现和调试错误的变量,同时产生没有明显的好处。

有什么你可以用的foreach DO循环这种方式,你不能,如果他们被编译的内部范围的变量,或者这只是一个任意选择那是在匿名方法和lambda前pressions是可利用的或共同制作,并且还没有被从那时起修改?


解决方案

Your criticism is entirely justified.

I discuss this problem in detail here:

Closing over the loop variable considered harmful

The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it made no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.

I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.

The for loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom.

这篇关于是否有一个foreach变量的C#的重用理由吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:34
查看更多