可能重复:
C#: using the iterator variable of foreach loop in a lambda expression - why fails?这个委托为什么不在循环内部工作?
我读在MSDN C#参考,我发现这个..
http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx
末注释中有一条评论通过albionmike
这是这样的..
When you "catpure" a variable from an outer scope, some counter-intuitive things happen.
If you run this, you will get an IndexOutOfRange exception during the call f().
If you uncomment the two commented out lines of code, it will work as expected.
Hint: Captured Outer Variables have reference rather than value semantics
// Console Project
using System;
using System.Collections.Generic;
using System.Text;
namespace EvilDelegation
{
delegate void PrintIt();
class Program
{
static void Main(string[] args)
{
string[] strings = { "zero", "one", "two", "three", "four" };
PrintIt f = null;
for (int i = 0; i < strings.Length; ++i) {
if (i == 2 || i == 3) {
// Can you see why this would not work?
f = delegate() { Console.WriteLine(strings[i]); };
// But this does...
//int k = i;
//f = delegate() { Console.WriteLine(strings[k]); };
}
}
f();
}
}
}
我不明白,为什么拳头一个不行,第二个会呢?在第四行,他说:Captured Outer Variables have reference rather than value semantics
。
好的,很好。但是在for循环中,我们将i
定义为int
,这当然是一个值类型,那么int
类型如何保存一个引用?如果i
不能持有参考,这意味着它存储的价值,如果它存储的价值,那么我不明白为什么第一个不会工作,第二个会?
我在这里错过了什么?
编辑:我认为最初的作者有一个错字,调用f()应该在if循环中。请在回答时考虑这一点。
编辑2:好的,如果有人可能会说,这不是一个错字,让我们考虑它是。我想知道在if
条款内拨打f()
的情况。两者都会在这种情况下运行,还是只有没有评论的那个?
这是从字面上[问18分钟前](http://stackoverflow.com/questions/11524532/delegate-method-inside-foreach-loop-always-binds-to-last-item)。 – 2012-07-17 14:40:16
@KirkWoll 那么,它不是我想出来的,并没有搜查,我发现它在MSDN上,并不明白,因此在这里问 – Razort4x 2012-07-17 14:41:49