闭包 Closure

http://en.wikipedia.org/wiki/Closure_(computer_science)

In computer science, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables) of that function.[1] A closure—unlike a plainfunction pointer—allows a function to access those non-local variables even when invoked outside of its immediate lexical scope.

The concept of closures was developed in the 1960s and was first fully implemented in 1975 as a language feature in the Scheme programming language to support lexically scoped first-class functions. The explicit use of closures is associated with functional programming languages such asLisp and ML, as traditional imperative languages such as AlgolC and Pascal did not support returning nested functions as results of higher-order functions and thus did not require supporting closures either. Many modern garbage-collected imperative languages (such as Smalltalk, the first object-oriented language featuring closures,[2] C#, but notably not Java[3]) support closures.

Python:

def counter():
    x = 0
    def increment(y):
        nonlocal x
        x += y
        print(x)
    return increment

C#:

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

namespace ClosureDemo
{
    public delegate int DelFun ();
    
    class Program
    {
        public static DelFun A(int y){
            int x = y;
            //DelFun d1 = delegate() { return x++; };
            //return d1;
            return delegate() { return x++; };
        }

        static void Main(string[] args)
        {
            DelFun f1 = A(10);
            DelFun f2 = A(20);
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("f1:" + f1());
                Console.WriteLine("f2:" + f2());
            }

                Console.ReadKey();
        }
    }
}

  

 

 

posted @ 2012-12-05 16:18  庚武  Views(229)  Comments(0Edit  收藏  举报