C#-Closure -Clarification [英] C# -Closure -Clarification

查看:121
本文介绍了C#-Closure -Clarification的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习C#。可我的意思是封闭的,可以采用在定义它的环境的变化的结构。

I am learning C#.Can I mean closure as a construct that can adopt the changes in the environment in which it is defined.

例如:

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; }); 
}



变量 ID 在FindPersonByID范围声明(),但难道我们仍然可以访问
局部变量 ID 匿名函数内(即)委托(人X){返回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)是我封的理解是否正确?

(1) Is my understanding of closure is correct ?

( 2)有什么优势我们可以从封闭得到什么?

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

推荐答案

是里面的代码 FindPersonByID 通过使用lambda表达式中的参数 ID 趁着一个封闭的。严格地说闭包的定义稍微复杂一些,但在基本层面上,这是正确的。如果您想对它们如何运作的更多信息,我建议您阅读以下文章

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

倒闭的主要优点是基本上是你在上面展示的东西。它可以让你写一个更自然的,直截了当的方式代码,而不必担心的是如何产生的lambda表达式实施细则(一般)

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)

考虑对例如,你需要多少代码在封闭的abscence写

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.

这篇关于C#-Closure -Clarification的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆