为什么在 C# 中需要部分方法?可以使用事件来实现相同的目标吗?
我正在阅读《Apress Pro LINQ:C# 中的语言集成查询》一书,我遇到了部分方法,但我真的不明白它们的需要是什么。
我认为书上的例子(改变前后的属性)可以使用事件来实现。那么有什么解释吗?
I was reading the book "Apress Pro LINQ: Language Integrated Query in C#" and I came across partial methods, but I really don't understand what is the need for them.
I think the examples in the book (properties before and after change) can be implemented using events. So any explanation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,您可以使用事件实现与使用部分方法类似的效果。分部方法实际上只是让代码生成器(主要是设计者)为非生成代码生成钩子的一种方法。活动可以填补这个角色。
然而,部分方法相对于事件有一些优点,特别是
Yes, you could achieve a similar effect with events as you can with partial methods. Partial methods are really just a way of letting code generators, primarily designers, to generate hooks for the non-generated code. Events could fill this role.
However there are advantages to partial methods over events in particular
如果没有实现,编译器将删除对部分方法的调用。使用事件的替代方案,必须在运行时检查侦听器(还需要存储它们等)。这使得部分方法的性能更高,特别是当有许多潜在的“事件”并且只有少数注册了“侦听器”时。
The compiler will remove calls to partial methods if there are no implementations. With the alternative of events, listeners would have to be checked at runtime (they would also need to be stored, etc). This allows partial methods to be more performant, especially when there are many of potential "events" and only a few have "listeners" registered.
它们不是“需要”的,而是大规模应用所需要的。事件的广泛使用会导致智能 UI 反模式,其中业务逻辑与用户界面紧密耦合,而部分功能可以让您更好地分离您的关注点。
这里还有关于部分方法的 MSDN C# 编程指南的链接。
http://msdn.microsoft.com/en-us/library/wa80x488。 ASPX
They are not "needed", but desired for large scale applications. Extensive use of events leads to the Smart UI anti-pattern where the business logic is tightly coupled with the user interface, whereas partial functions allow you to better separate your concerns.
Here is a link to the MSDN C# programming guide on partial methods as well.
http://msdn.microsoft.com/en-us/library/wa80x488.aspx
部分方法在编译时定义,事件在运行时定义。所以它们是不同的东西。
部分方法被引入图片中以扩展您无法控制的现有类(框架的一部分或自动生成的)
希望这有帮助
Partial methods are defined at compile time, events at runtime. So they are different things.
Partial methods were brought to the picture to extend existing classes that you have no control over (part of the framework or auto-generated)
Hope this helps