Conditional Delegate?
After the user is done with form "f", the form will retain a value that I want to check before running doStuff(). Like, if f.value > 0 , then run doStuff(), else, don't run doStuff(). How can I most concisely modify my code to allow for this check? I don'开发者_StackOverflow社区t quite understand when the delegate is assigned, if I pass f.value, will it take the value when I'm adding the delegate, or when it is running the delegate?
form f = new form();
f.Show();
f.FormClosing += delegate{doStuff();};
Thanks!
You can capture the value of the reference when making the delegate:
f.FormClosing += delegate { if(f.value > 0) doStuff(); };
When the event occurs, it will check the current value of the captured reference f
, and if the condition matches, continue executing.
form f = new form();
f.Show();
f.FormClosing += delegate{if(f.Value>0){doStuff();}};
I believe that it uses the value at the time it runs, not at the time it is assigned. So it would use the value of f.Value when the FormClosing event fires
Somthing like this?
form f = new Form();
f.Show();
f.FormClosing += (s, a) =>
{
if (f.Value > 0)
{
doStuff();
}
};
My understanding is that lambdas are run in the scope that they're defined, so...
form f = new form();
f.Show();
f.FormClosing += delegate
{
if(f.Value > 0)
doStuff();
};
You can use regular syntax to implement it
form f = new form();
f.FormClosing += FormClosingHandler; // Add unanonaymous delegate to the event handler
f.Show();
private void FormClosingHandler(object sender, FormClosingEventArgs e)
{
var form = (form)sender;
form.FormClosing -= FormClosingHandler; // Unsubscribe from the event to prevent memory leak
if(form.value > 0)
{
doStuff();
}
}
I wouldn't do it this way. I'd let the form handle it all. Just run the form...
public void showMyForm()
{
form f = new form();
f.Show();
}
...then define the form closing event in the form .cs file and link the event in the form itself...
public partial class form : Form
{
//Link the event in the IDE and let InitializeComponent() add it. Then perform the
//the things you want in the form itself based on your condition
private void doStuff(object sender, FormClosingEventArgs e) //Think that's the right args
{
if (this.value > 0)
{
//code you want to execute.
}
}
}
If f.Value is a member of the form it will be checked when the delegate is run and you will get the value that is assigned at that moment, not at the moment you assigned the delegate.
精彩评论