Scenarios when to use closures
I've played with closures a bit in C# and even written them in production-spec apps, however, nothing has really shouted at me that this problem must be, or can only be, solved with the use of a closure.
Is there any problem where closures are particularly useful for solvin开发者_如何学JAVAg? Also, is there any gotcha with closures in C# 4.0?
Thanks
Given that closures are a compiler feature rather than a platform feature, there's nothing which can't be done with them.
You can write all the code which the compiler uses by hand (well, with a few exceptions when it comes to expression trees, and the compiler has access to some IL instructions which aren't exposed by the language).
However, you'd be mad not to use closures in LINQ where you need access to the enclosing variables. For example:
public List<Person> FilterByAge(IEnumerable<Person> people, int age)
{
return people.Where(p => p.Age >= age).ToList();
}
That lambda expression is a closure, accessing age
from within a delegate.
As for gotchas:
- Closing over the loop variable considered harmful
- Generic variance doesn't play well with combining delegates
- Just getting your head round everything :)
精彩评论