Home > other >  How to store functions and arguments to execute later?
How to store functions and arguments to execute later?

Time:12-10

Suppose I have a 3 functions:

void A(int i){...}
void B(bool b, string s){...}
void C(float f, double d, char c){...}

In my application, in a given moment, I open a popup that has a button. My popup has a controller (called PopupController). It has references for everything in the popup and includes the function OnButtonPress(), called by the button at pressing.

My question is how to make the popup button execute those 3 functions with given parameter?

...
var popupController = PopupController.CreateInstance();
//I wanna execute this only at button press:
A(1);
B(true, "s");
C(1, 2, 'c');

How can I do this? I'm allowed to create whatever is needed to store these functions in the PopupController.

CodePudding user response:

delegates; for example

Action thing = () => A(1);

or

EventHandler handler = delegate {
    A(1);
    B(true, "s");
    C(1, 2, 'c');
};

then invoke that delegate later when needed, for example thing(); or handler(this, EventArgs.Empty);.

this is even easier if the button-press is itself an event:

btn.Click  = delegate {
    A(1);
    B(true, "s");
    C(1, 2, 'c');
};
  • Related