Partial Classes in C#

后端 未结 20 2891
广开言路
广开言路 2021-02-19 08:25

Are there are good uses of Partial Classes outside the webforms/winforms generated code scenarios? Or is this feature basically to support that?

20条回答
  •  终归单人心
    2021-02-19 08:44

    Code generation was the driving force behind partial classes. The need comes from having a code-generated class that is constantly changing, but allow developers to supply custom code as part of the class that will not be overridden everytime changes are made that force the class to be regenerated.

    Take WinForms or Typed-DataSets for example (or any designer for that matter). Everytime you make a change to the designer it serializes the corresponding code to a file. Let's say you need to provide a few additional methods that the generator doesn't know anything about. If you added it to the generated file your changes would be lost the next time it was generated.

    A project that I'm currently working on uses code-generation for all the DAL, BLL, and business entities. However, the generator only get's us 75% of the information. The remaining portion has to be hand coded (custom business logic for instance). I can assume that every BLL class has a SelectAll method, so that's easy to generate. However My customer BLL also needs to have a SelectAllByLocation method. I can't put this in my generator because it's not generic to all BLL classes. Therefore I generate all of my classes as partial classes, and then in a separate file I define my custom methods. Now down the road when my structure changes, or I need to regenerate my BLL for some reason, my custom code won't get wiped out.

提交回复
热议问题