海底的八爪鱼

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

以下代码,在Fx 2.0 下通过。

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    
delegate void 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;
        }

        
static void 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);
                            
return null;

                        }
;
                        
return j;
                    }
;
                    
return s;

                }
;
                
return q;
            }
;
            
return p;
        }

        
static void Main(string[] args)
        
{
            t f 
= p();
            t q 
= f();
            t j 
= q();
            j();
        }

    }

}



可谓潜力无限。
posted on 2005-05-07 13:42  八爪鱼  阅读(143)  评论(0)    收藏  举报