Can someone explain it to me what closure is in re

2019-03-13 02:27发布

Possible Duplicate:
What are ‘closures’ in .NET?

I am currently looking at lambda expression and the word closure keeps coming. Can someone explain it to me in real simple language.

9条回答
乱世女痞
2楼-- · 2019-03-13 03:24

If the 5 year old knew C#, I would explain with this code sample:

int i = 0;
string result = null;
Action iExaminer = () =>
{
  result = i % 2 == 1 ? "Odd" : "Even";
};
i = 1;
iExaminer();
Console.WriteLine(result);

If the 5 year old was learning linq, I would explain with this code sample:

string name = null;
IEnumerable<Customer> query = Customers.Where(c => c.Name == name);
name = "Bob";
 // query is resolved when enumerated (which is now)
 // Where will now call our anonymous method.
foreach(var customer in query)
{
  Console.WriteLine(customer.Name);
}
查看更多
姐就是有狂的资本
3楼-- · 2019-03-13 03:25

When you know how to do something in general, you can specify some (or all) details and get a closure.

For example, you know how to buy ice-cream. Yyou know what to do if you will be in front of any shop. But if you want to go to a particular shop (for example, due to a Sunday discount), you move out of house with the aim of buying ice-cream there. "Buy some ice-cream at a store on the corner" is a closure of "buy some ice-cream". In fact, all these are closures of "buy some ice-cream somewhere":

  • Buy some ice-cream at the corner
  • Buy two ice-creams
  • Buy two ice-creams at the corner

Now go play with your friends, son! (and I bear in mind not say anything like that in front of the children)

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-03-13 03:27

This is a simple approach to the idea in C#: Closure

查看更多
登录 后发表回答