c# - Different delegates in loop -


this question has answer here:

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

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -