【发布时间】:2010-10-31 15:41:40
【问题描述】:
编写内联事件处理程序是不好的做法吗?
对我来说,当我想在事件处理程序中使用局部变量时,我更喜欢使用它,如下所示:
我更喜欢这个:
// 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();
}
而不是这个:
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();
}
【问题讨论】:
-
是的,lambda 和闭包肯定是邪恶的......
-
我认为这取决于您的团队。如果每个人都对这些功能感兴趣,那很好。我个人喜欢在单独的行上使 lambdas 更明显,等等。我喜欢这样编码,以便 1 行代码做 1 件事。
-
+1 @kenny 我同意你的观点,这使代码更清晰。
-
也同意肯尼的观点。一旦您接受了 Jon 的回答并确定从技术角度(性能、可扩展性等)来说没问题,好的/坏的做法就是预测谁将在以后阅读或修改此代码以及他们将如何看待它,包括您自己在你忘记它的作用之后。
标签: c# event-handling inline-code