简体   繁体   English

C#-关闭-澄清

[英]C# -Closure -Clarification

I am learning C#.Can I mean closure as a construct that can adopt the changes in the environment in which it is defined. 我正在学习C#。我的意思是说闭包是a construct that can adopt the changes in the environment in which it is defined.

Example : 范例:

List<Person> gurus = 
new List<Person>()
                 {
                  new Person{id=1,Name="Jon Skeet"},
                  new Person{id=2,Name="Marc Gravell"},
                  new Person{id=3,Name="Lasse"}
                 };            


void FindPersonByID(int id)
{
  gurus.FindAll(delegate(Person x) { return x.id == id; }); 
}

The variable id is declared in the scope of FindPersonByID() but t we still can access the local variable id inside the anonymous function (ie) delegate(Person x) { return x.id == id; } 变量id在FindPersonByID()的范围内声明,但我们仍然可以在匿名函数内访问局部变量id (即, delegate(Person x) { return x.id == id; } delegate(Person x) { return x.id == id; }

(1) Is my understanding of closure is correct ? (1)我对闭包的理解正确吗?

(2) What are the advantages can we get from closures? (2)从闭包中可以获得什么好处?

Yes the code inside of FindPersonByID is taking advantage of a closure by using the parameter id within the lambda expression. 是的, FindPersonByID内部的代码通过使用lambda表达式中的参数id来利用闭包。 Strictly speaking the definitions of closures are a bit more complex but at a basic level this is correct. 严格说来,闭包的定义要复杂一些,但从根本上讲这是正确的。 If you want more information on how they function I encourage you to read the following articles 如果您想了解有关其功能的更多信息,建议您阅读以下文章

The primary advantage of closures is essentially what you demonstrated above. 闭包的主要优点本质上就是您上面展示的内容。 It allows you to write the code in a more natural, straight forward fashion without having to worry about the implementation details of how the lambda expression is generated (generally) 它使您可以以更自然,直接的方式编写代码,而不必担心lambda表达式如何生成的实现细节(通常)

Consider for example how much code you would have to write in the abscence of closures 例如,考虑在闭包缺失时必须编写多少代码

class Helper {
  private int _id;
  public Helper(int id) { 
    _id = id;
  }
  public bool Filter(Person p) {
    return p.id == _id;
  }
}

void FindPersonsByID(int id) {
  Helper helper = new Helper(id);
  gurus.FindAll(helper.Filter);
}

All of this just to express the concept of using a parameter inside of a delegate. 所有这些只是为了表达在委托内部使用参数的概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM