定义事件处理程序
我可以这样定义一个事件(声明的函数):
MyElement.Keyup +=MyDeclaredFunction
我也可以这样定义它(匿名委托):
MyElement.Keyup+=new delegate(object sender, eventargs e) {};
我也可以这样定义它(lambda):
MyElement.Keyup += (sender, e) => myfunction
最好的方法是什么?一种情况是事件的代码与事件的声明一起找到……另一种情况是它们是分开的。
我更喜欢方法 1
谁能告诉我每种方法的优缺点是什么?
I can define an event like this(declared function):
MyElement.Keyup +=MyDeclaredFunction
I can also define it like this(anonymous delegate):
MyElement.Keyup+=new delegate(object sender, eventargs e) {};
I can also define it like this(lambda):
MyElement.Keyup += (sender, e) => myfunction
What is the best way to do this? One case the code for the event is found with the declaration of the event... in the other they are seperated.
I prefer method 1
can anyone tell me what the pros and cons of each method might be?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
方法2和3是一样的。
在方法 1 中,您可以稍后取消订阅事件。在方法 2 中,您无法取消订阅事件。我想说这是主要区别。
Methods 2 and 3 are the same.
In method 1 you can later unsubscribe from event. In method 2 you can not unsubscribe from event. I would say this is main difference.
第一个对于大量代码或您想要重用代码的情况是有用且正常的(您可以通过捕获到变量中使用匿名方法来完成此操作,但它失去了光泽有点...)
第二个和第三个基本相同(至少在 C# 3.0 中),并且对于短代码块来说非常方便。实际上,还有第四个选项,如果您不关心参数,则很有用:
请注意,我们不必声明任何参数(编译器编写了一个不使用它们的兼容签名)。上面的技巧对于
Click
事件可能不太方便(我猜对于KeyUp
你感兴趣的是按下了哪个键,所以可能不< /strong> 在您的场景中使用这个)。The first is useful and normal for non-trivial amounts of code, or where you want to re-use code (you can do this with an anonymous method by capturing into a variable, but it loses the shine somewhat...)
The second and third are largely identical (in C# 3.0, at least), and are really handy for short blocks of code. Actually, there is a 4th option, useful if you don't care about the args:
Note we haven't had to declare any args (the compiler writes a compatible signature that just doesn't use them). The above trick is probably mot handy for
Click
events (I'm guessing that forKeyUp
you are interested in which key was pressed, so probably don't use this one in your scenario).每当我知道我需要在代码中稍后的某个时刻取消订阅事件时,我更喜欢在附加到事件时使用附加/分离模式。
使用 Labda 和匿名方法不允许我们这样做,除非我们将匿名方法或 lambda 分配给委托变量。
我想说,在 (1) 中使用声明的一个优点是该方法将在类中的其他位置声明,这使得开发人员可以轻松“扫描”您的代码并发现事件处理程序方法,而匿名方法和lambda 可以在需要的地方声明,如果不阅读声明它们的方法的代码,这可能并不明显。
I prefer to use the attach/detach pattern when attaching to events whenever I know that I will need to unsubscribe from an event at some later point in my code.
Using labdas and anonymous methods do not allow us to do this unless we assign the anonymous methods or lambdas to delegate variables.
I would say the one pro of using decalration in (1) is that the method will be declared elsewhere within your class and this makes it easy for a developer to "scan" your code and discover the event handlers methods, whereas the anonymous methods and lambdas can be declared right where they are needed and it might not be obvious without reading the method's code that declares them.