C# -Closure -Clarification

纵饮孤独 提交于 2019-11-27 02:49:07

问题


I am learning C#.Can I mean closure as 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 (i.e) delegate(Person x) { return x.id == id; }

(1) Is my understanding of closure is correct ?

(2) What are the advantages can we get from closures?


回答1:


Yes the code inside of FindPersonByID is taking advantage of a closure by using the parameter id within the lambda expression. 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

  • http://csharpindepth.com/Articles/Chapter5/Closures.aspx
  • http://blogs.msdn.com/jaredpar/archive/tags/Closures/default.aspx

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)

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.



来源:https://stackoverflow.com/questions/2528603/c-sharp-closure-clarification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!