In the following example, the anonymous method references instance members of this:
下面的例子中,你名方法引用了this的實例成員:
class Test { int x;
void F() { D d = delegate { Console.WriteLine(x); }; } }
This can be translated to a compiler generated instance method containing the code of the anonymous method:
它會被翻譯為一個編譯器生成的實例方法,該方法包含了匿名方法中的代碼:
class Test { int x;
void F() { D d = new D(__Method1); }
void __Method1() { Console.WriteLine(x); } }
In this example, the anonymous method captures a local variable:
在這個例子中,匿名方法捕獲了一個局部變量:
class Test { void F() { int y = 123; D d = delegate { Console.WriteLine(y); }; } }
The lifetime of the local variable must now be extended to at least the lifetime of the anonymous method delegate. This can be achieved by “lifting” the local variable into a fIEld of a compiler generated class. Instantiation of the local variable (§21.5.2) then corresponds to creating an instance of the compiler generated class, and accessing the local variable corresponds to Accessing a fIEld in the instance of the compiler generated class. Furthermore, the anonymous method becomes an instance method of the compiler generated class:
class Test { void F() { __locals1 = new __Locals1(); __locals1.y = 123; D d = new D(__locals1.__Method1); }
class __Locals1 { public int y; public void __Method1() { Console.WriteLine(y); } } }
Finally, the following anonymous method captures this as well as two local variables with different lifetimes:
最後,下面的匿名方法捕獲了this和兩個具有不同生存期的局部變量:
class Test { int x;
void F() { int y = 123;
for (int i = 0; i < 10; i++) { int z = i * 2; D d = delegate { Console.WriteLine(x + y + z); }; } } }
Here, a compiler generated class is created for each statement block in which locals are captured such that the locals in the different blocks can have independent lifetimes. An instance of __Locals2, the compiler generated class for the inner statement block, contains the local variable z and a field that references an instance of __Locals1. An instance of __Locals1, the compiler generated class for the outer statement block, contains the local variable y and a fIEld that references this of the enclosing function member. With these data structures it is possible to reach all captured outer variables through an instance of __Local2, and the code of the anonymous method can thus be implemented as an instance method of that class.
class Test { void F() { __locals1 = new __Locals1(); __locals1.__this = this; __locals1.y = 123;
for (int i = 0; i < 10; i++) { __locals2 = new __Locals2(); __locals2.__locals1 = __locals1; __locals2.z = i * 2; D d = new D(__locals2.__Method1); } }
class __Locals1 { public Test __this; public int y; }
class __Locals2 { public __Locals1 __locals1; public int z;