它是不好的做法,编写内联事件处理程序 [英] Is it bad practice to write inline event handlers

查看:93
本文介绍了它是不好的做法,编写内联事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是不好的做法,编写内联事件处理程序?



对于我来说,我更喜欢使用它时,我想用一个局部变量在事件处理程序像下面



我更喜欢这样的:

  //这仅仅是一个样品
私人无效美孚()
{
定时器定时器=新的Timer(){间隔= 1000};
INT计数器= 0; //计数器刚刚这个使命
timer.Tick + =(S,E)=> myTextBox.Text =(计数器++)的ToString()。
timer.Start();
}



而不是这样的:

  INT计数器= 0; //不需要这一点嘘声和放大器;事件处理程序

私人无效嘘()
{
定时器定时器=新的Timer(){间隔= 1000};

timer.Tick + = timer_Tick;
timer.Start();
}

无效timer_Tick(对象发件人,EventArgs五)
{
myTextBox.Text =(计数器++)的ToString()。
}


解决方案

这绝对是很好 - 虽然有有两点需要说明:




  • 如果您正在修改从封闭中的一个局部变量,你要确保你知道你在做什么

  • 您将无法从事件



通常情况下,我只内嵌退订的真正的简单的事件处理程序 - 任何东西更多地参与,我用lambda表达式(或匿名方法)与呼叫订阅的方法,用更适当的方法:

  //我们不关心这里的论点; SaveDocument不应该需要的参数
saveButton.Click + = {委托SaveDocument(); };


Is it bad practice to write inline event handlers ?

For me, I prefer use it when I want to use a local variable in the event handler like the following:

I prefer this:

// 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();
}

Instead of this:

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();
}

解决方案

It's absolutely fine - although there are two caveats:

  • If you're modifying a local variable from within a closure, you should make sure you understand what you're doing.
  • You won't be able to unsubscribe from the event

Typically I only inline really simple event handlers - for anything more involved, I use lambda expressions (or anonymous methods) to subscribe with a call to an method with a more appropriate method:

// We don't care about the arguments here; SaveDocument shouldn't need parameters
saveButton.Click += delegate { SaveDocument(); };

这篇关于它是不好的做法,编写内联事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆