using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
delegatevoid t();
class Program
{
bool c =false;
t p()
{
int i;
if (!c)
{
i =2;
c =true;
} else {
i =1;
} t f=delegate(){System.Console.WriteLine(i);};
return f;
} staticvoid Main(string[] args)
{
Program h=new Program();
t f = h.p();
t q = h.p();
f();
q();
} } }
Fx 2.0 在处理 yield return 时,使用状态机来捕获内部状态。看来在这里也使用了类似的技术。
进一步说,这种技术可在函数执行的任意时候,将状态捕捉下来,并可供继续执行。如下所演示
namespace ConsoleApplication1
{
delegate t t();
class Program
{
static t p()
{
int i =3;
t p =delegate {
System.Console.WriteLine(i);
t q =delegate {
i--;
System.Console.WriteLine(i);
t s =delegate {
i--;
System.Console.WriteLine(i);
t j =delegate {
i--;
System.Console.WriteLine(i);
returnnull;
};
return j;
};
return s;
};
return q;
};
return p;
} staticvoid Main(string[] args)
{
t f = p();
t q = f();
t j = q();
j();
} } }