가능한 중복 :
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();
}
}
}
주먹이 작동하지 않는 이유는 무엇이며, 두 번째 것은 작동합니까? 제 4 라인에서 그는 다음과 같이 말합니다 : Captured Outer Variables have reference rather than value semantics
.
좋습니다. 그러나 for 루프에서 i
을 int
으로 정의했는데 이는 값 유형이므로 int
유형이 참조를 보유 할 수있는 방법은 무엇입니까? 그리고 i
이 참조를 보유 할 수 없다면 이는 값을 저장한다는 것을 의미하며 값을 저장하는 경우 첫 번째 값은 작동하지 않고 두 번째 값은 저장되지 않습니다.
여기에 뭔가가 있습니까?
편집 : 원본 작성자는 f() 호출이 오타가있는 것으로 생각합니다. 응답하는 동안 이것을 고려하십시오.
EDIT 2 : 좋아, 누군가가 말하면, 오타가 아니라고 생각해 봅시다. f()
에 대한 전화가 if
절 안에서 이루어진 경우를 알고 싶습니다. 이 경우 둘 다 실행되거나 주석이없는 사람이 둘 중 하나입니까?
이것은 문자 그대로 [Ask 18 minutes ago] (http://stackoverflow.com/questions/11524532/delegate-method-inside-foreach-loop-always-binds-to-last-item)입니다. –
@KirkWoll 글쎄, 내가 그걸 생각해 내지 않았고, 검색하지 않았고, MSDN에서 찾았고 이해할 수 없었기 때문에 여기에 묻습니다. – Razort4x