Why you need partial methods in c#? Can events be used to achieve the same goal?

徘徊边缘 提交于 2019-11-30 01:55:42

问题


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?


回答1:


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

  • Partial method calls are completely removed from the generated IL if there is no implementation. This cannot be done with events.
  • The design of partial methods is to solve the problem where there is 1 provider of the hook and 1 consumer. Events are meant to model 1 provider with N consumers and have the overhead which comes with such a design
  • There is no issue of ordering (who goes first). With events you need to ensure the code which subscribes to the event runs before the designer generated code that raises the event. This is not always possible if say the designer generates a constructor. Partial methods have no such issue.



回答2:


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




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/3628804/why-you-need-partial-methods-in-c-can-events-be-used-to-achieve-the-same-goal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!