Hom*_*mam 58 c# event-handling inline-code
编写内联事件处理程序是不好的做法吗?
对我来说,当我想在事件处理程序中使用局部变量时,我更喜欢使用它,如下所示:
我更喜欢这个:
// This is just a sample
private void Foo()
{
Timer timer = new Timer() { Interval = 1000 };
int counter = 0; // counter has just this mission
timer.Tick += (s, e) => myTextBox.Text = (counter++).ToString();
timer.Start();
}
Run Code Online (Sandbox Code Playgroud)
而不是这个:
int counter = 0; // No need for this out of Boo & the event handler
private void Boo()
{
Timer timer = new Timer() { Interval = 1000 };
timer.Tick += timer_Tick;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
myTextBox.Text = (counter++).ToString();
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 76
这绝对没问题 - 虽然有两点需要注意:
通常我只内联非常简单的事件处理程序 - 对于任何更复杂的事情,我使用lambda表达式(或匿名方法)通过使用更合适的方法调用方法来订阅:
// We don't care about the arguments here; SaveDocument shouldn't need parameters
saveButton.Click += delegate { SaveDocument(); };
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35251 次 |
| 最近记录: |