c# - Different delegates in loop -
this question has answer here:
- captured variable in loop in c# 6 answers
is possible have delegates declared in loop perform different actions?
var buttons = new list<imagebutton>(); buttons.add(findviewbyid<imagebutton>(resource.id.button1)); buttons.add(findviewbyid<imagebutton>(resource.id.button2)); int count = 1; foreach(var button in buttons) { button.click += delegate { toast.maketext(this, "i " + count, toastlength.short).show(); } count++; }
the toast message "i 2" when clicking either button. have number of buttons performing different actions when clicked.
you've got single count
variable, , anonymous method captures it. means when delegate executed, use current value of variable. want "the value of count
when delegate created" means want different variable on each iteration. it's simplest declare variable within loop:
int count = 1; foreach(var button in buttons) { // each iteration create "new" copy variable, // value never changes int copy = count; button.click += delegate { toast.maketext(this, "i " + copy, toastlength.short).show(); } count++; }
Comments
Post a Comment