What are 'closures' in .NET?

前端 未结 12 1911
执念已碎
执念已碎 2020-11-21 13:53

What is a closure? Do we have them in .NET?

If they do exist in .NET, could you please provide a code snippet (preferably in C#) explaining it?

12条回答
  •  感动是毒
    2020-11-21 14:25

    A closure is a function, defined within a function, that can access the local variables of it as well as its parent.

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

    so the function inside the find method.

     t => t.Name == name
    

    can access the variables inside its scope, t, and the variable name which is in its parents scope. Even though it is executed by the find method as a delegate, from another scope all together.

提交回复
热议问题