什么是闭包?我们在。net中有吗?

如果它们确实存在于。net中,你能提供一个代码片段(最好是c#)来解释它吗?


当前回答

闭包是在函数中定义的函数,可以访问它的局部变量以及它的父变量。

public string GetByName(string name)
{
    List<things> theThings = new List<things>();
    return  theThings.Find<things>(t => t.Name == name)[0];
}

find方法中的函数。

t => t.Name == name

可以访问其作用域中的变量t,以及父作用域中的变量名。即使它是由find方法作为委托从另一个作用域执行的。

其他回答

下面是我从JavaScript中类似的代码创建的c#人为示例:

public delegate T Iterator<T>() where T : class;

public Iterator<T> CreateIterator<T>(IList<T> x) where T : class
{
    var i = 0; 
    return delegate { return (i < x.Count) ? x[i++] : null; };
}

所以,这里有一些代码,展示了如何使用上面的代码…

var iterator = CreateIterator(new string[3] { "Foo", "Bar", "Baz"});

// So, although CreateIterator() has been called and returned, the variable 
// "i" within CreateIterator() will live on because of a closure created 
// within that method, so that every time the anonymous delegate returned 
// from it is called (by calling iterator()) it's value will increment.

string currentString;    
currentString = iterator(); // currentString is now "Foo"
currentString = iterator(); // currentString is now "Bar"
currentString = iterator(); // currentString is now "Baz"
currentString = iterator(); // currentString is now null

希望这对大家有所帮助。

闭包是在函数中定义的函数,可以访问它的局部变量以及它的父变量。

public string GetByName(string name)
{
    List<things> theThings = new List<things>();
    return  theThings.Find<things>(t => t.Name == name)[0];
}

find方法中的函数。

t => t.Name == name

可以访问其作用域中的变量t,以及父作用域中的变量名。即使它是由find方法作为委托从另一个作用域执行的。

如果你有兴趣了解c#如何实现闭包,请阅读“I know the answer (its 42) blog”。

编译器在后台生成一个类来封装匿名方法和变量j

[CompilerGenerated]
private sealed class <>c__DisplayClass2
{
    public <>c__DisplayClass2();
    public void <fillFunc>b__0()
    {
       Console.Write("{0} ", this.j);
    }
    public int j;
}

对于函数:

static void fillFunc(int count) {
    for (int i = 0; i < count; i++)
    {
        int j = i;
        funcArr[i] = delegate()
                     {
                         Console.Write("{0} ", j);
                     };
    } 
}

把它变成:

private static void fillFunc(int count)
{
    for (int i = 0; i < count; i++)
    {
        Program.<>c__DisplayClass1 class1 = new Program.<>c__DisplayClass1();
        class1.j = i;
        Program.funcArr[i] = new Func(class1.<fillFunc>b__0);
    }
}

闭包是在另一个函数(或方法)中定义的函数,它使用父方法中的变量。这种位于方法中并包装在其中定义的函数中的变量的使用称为闭包。

Mark Seemann在他的博客文章中有一些关于闭包的有趣例子,他将面向对象编程和函数式编程进行了比较。

让它更详细

var workingDirectory = new DirectoryInfo(Environment.CurrentDirectory);//when this variable
Func<int, string> read = id =>
    {
        var path = Path.Combine(workingDirectory.FullName, id + ".txt");//is used inside this function
        return File.ReadAllText(path);
    };//the entire process is called a closure.

基本上闭包是一段代码,你可以把它作为参数传递给函数。c#支持匿名委托形式的闭包。

这里有一个简单的例子: 列表。Find方法可以接受并执行一段代码(闭包)来查找列表的项。

// Passing a block of code as a function argument
List<int> ints = new List<int> {1, 2, 3};
ints.Find(delegate(int value) { return value == 1; });

使用c# 3.0语法,我们可以这样写:

ints.Find(value => value == 1);