C# 中的“闭包”是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/595482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:39:40  来源:igfitidea点击:

What are 'closures' in C#?

c#closures

提问by Shane Scott

Duplicate

复制

Closures in .NET

.NET 中的闭包

What are closures in C#?

C#中的闭包是什么?

采纳答案by cgreeno

A closurein C# takes the form of an in-line delegate/anonymous method. A closureis attached to its parent method meaning that variables defined in parent's method body can be referenced from within the anonymous method. There is a great Blog Posthere about it.

C# 中的闭包采用内联委托/匿名方法的形式。甲闭合连接到它的父方法意味着在父母的方法体定义的变量可以从匿名方法中被引用。这里有一篇很棒的博客文章

Example:

例子:

public Person FindById(int id)
{
    return this.Find(delegate(Person p)
    {
        return (p.Id == id);
    });
}

You could also take a look at Martin Fowleror Jon Skeetblogs. I am sure you will be able to get a more "In Depth" breakdown from at least one of them....

您还可以查看Martin FowlerJon Skeet 的博客。我相信您将能够从其中至少一个中获得更“深入”的细分......

Example for C# 6:

C# 6 的示例:

public Person FindById(int id)
{
    return this.Find(p => p.Id == id);
}

which is equivalent to

这相当于

public Person FindById(int id) => this.Find(p => p.Id == id);