4 ms·
You could try an example showing what a closure does 'under the hood' by showing an equivalent non-closure example, like: With Closure: foreach (var obj in
by rleisti 17y ago
You could try an example showing what a closure does 'under the hood' by showing an equivalent non-closure example, like:
With Closure:
foreach (var obj in objects) {
AddButton("Delete " + obj.ToString(), () => obj.Delete());
}
Without closure:
class DeleteHandler {
public DeleteHandler(TYPE obj) {
_obj = obj;
}
private TYPE obj;
public void DoDelete() {
obj.delete();
}
}
...
foreach(var obj in objects) {
var deleteHandler = new DeleteHandler(obj);
AddButton("Delete " + obj.ToString(), deleteHandler.DoDelete);
}
- tome 17y agoI'm not convinced by the utility of your example. What's wrong with: foreach (var obj in objects) { AddButton("Delete " + obj.ToString(), obj.Delete); } This is even simpler and doesn't use closures at all.
- rleisti 17y agoDoh! It would have made more sense if I had some other piece of information to inject in, like if you had a database reference that needed to be passed in to the Delete() method. Then: AddButton("Delete " + obj.ToString(), () => obj.Delete(db)); Vs. var d = new DeleteHandler(obj, db); AddButton("Delete " + obj.ToString(), d.DoDelete); EDIT: fixed
- tome 17y agoYup, makes more sense now! This is a good example, I think, to give to people who are used to objects being used for everything. Nice, clean, functional syntax. (And of course you mean "d.DoDelete")