C# 事件处理程序问题
关于 C# 中的事件处理程序的简单问题,假设我们有以下代码:
MyObject.MyEventHandler += (...)
我当前正在重构一些代码,并且 (...) 经常被另一个事件处理程序替换,如下所示:
EventHandler A;
Test()
{
A += A_Method;
MyObject.MyEventHandler += A
}
忽略“A”不是更简单吗?而是写:
Test()
{
MyObject.MyEventHandler += A_Method;
}
如果我们可以直接将方法从“MyObject”传递给EventHandler对象,那么EventHandler“A”有什么用?
谢谢 !
Quick question regarding EventHandlers in C#, let's say we have the following code:
MyObject.MyEventHandler += (...)
I am currently refactoring some code, and the (...) is often replaced with another eventhandler, as such :
EventHandler A;
Test()
{
A += A_Method;
MyObject.MyEventHandler += A
}
Wouldn't it be simpler to disregard "A" and just write instead:
Test()
{
MyObject.MyEventHandler += A_Method;
}
What is the use of EventHandler "A", if we can just directly pass the method to the EventHandler object from "MyObject" ?
Thanks !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设你的意思是
(A_Method 之后没有括号)。如果是这样,假设没有什么比这个例子更复杂的事情了,
A
可能可以安全地省略。重构时,F12(转到定义)是你的朋友:找到所有引用并确保它们都正确地重新路由,等等。I assume you mean
(without parentheses after A_Method). If so, assuming that there is nothing more complex around this than the example,
A
can probably be safely omitted. When refactoring, F12 (go to definition) is your friend: find all references and make sure they all are properly re-routed, etc.当然可以,只要
A
不在其他地方使用即可。否则,可能需要进行重构以减少代码重复。Sure, as long as
A
isn't used other places. Otherwise it might have been a refactoring to reduce code duplication.