When is it appropriate to use C# partial classes?

2019-01-02 16:24发布

I was wondering if someone could give me an overview of why I would use them and what advantage I would gain in the process.

21条回答
怪性笑人.
2楼-- · 2019-01-02 16:57

Most people remark that partial should only be used for a class that has a generated code file or for interfaces. I disagree, and here is why.

For one example, let's look at the C# System.Math class... that's class. I would not attempt to stuff 70+ methods all into the same single code file. It would be a nightmare to maintain.

Placing each math method into individual partial class files, and all code files into a Math folder in the project, would be significantly cleaner organization.

The same could/would hold true for many other classes that have a large amount of diverse functionality. For example a class for managing the PrivateProfile API might benefit by being split into a clean set of partial class files in a single project folder.

Personally, I also split what most people call "helper" or "utility" classes into individual partial files for each method or method functional group. For example on one project the string helper class has almost 50 methods. That would be a long unwieldy code file even using regions. It is significantly easier to maintain using individual partial class files for each method.

I would just be careful using partial classes and keep all code file layout consistent throughout the project when doing this. Such as placing any class public enums and class private members into a Common.cs or similarly named file in the folder, instead of spreading them out across the files unless they are specific to only the partial file they are contained in.

Keep in mind that when you split a class into separate files you also lose the ability to use the text editor splitter bar that lets you view two different sections of a current file simultaneously.

查看更多
旧时光的记忆
3楼-- · 2019-01-02 17:00

keep everything as clean as possible when working with huge classes, or when working on a team, you can edit without overriding (or always commiting changes)

查看更多
春风洒进眼中
4楼-- · 2019-01-02 17:02

The biggest use of partial classes is to make life easier for code generators / designers. Partial classes allow the generator to simply emit the code they need to emit and they do not have to deal with user edits to the file. Users are likewise free to annotate the class with new members by having a second partial class. This provides a very clean framework for separation of concerns.

A better way to look at it is to see how designers functioned before partial classes. The WinForms designer would spit out all of the code inside of a region with strongly worded comments about not modifying the code. It had to insert all sorts of heuristics to find the generated code for later processing. Now it can simply open the designer.cs file and have a high degree of confidence that it contains only code relevant to the designer.

查看更多
浅入江南
5楼-- · 2019-01-02 17:03

From MSDN:

1.At compile time, attributes of partial-type definitions are merged. For example, consider the following declarations:

[SerializableAttribute]
partial class Moon { }

[ObsoleteAttribute]
partial class Moon { }

They are equivalent to the following declarations:

[SerializableAttribute]
[ObsoleteAttribute]
class Moon { }

The following are merged from all the partial-type definitions:

  • XML comments

  • interfaces

  • generic-type parameter attributes

  • class attributes

  • members

2.Another thing, nested partial classes can be also partial:

partial class ClassWithNestedClass
{
    partial class NestedClass { }
}

partial class ClassWithNestedClass
{
    partial class NestedClass { }
}
查看更多
唯独是你
6楼-- · 2019-01-02 17:06

Aside from the other answers...

I've found them helpful as a stepping-stone in refactoring god-classes. If a class has multiple responsibilities (especially if it's a very large code-file) then I find it beneficial to add 1x partial class per-responsibility as a first-pass for organizing and then refactoring the code.

This helps greatly because it can help with making the code much more readable without actually effecting the executing behavior. It also can help identify when a responsibility is easy to refactor out or is tightly tangled with other aspects.

However--to be clear--this is still bad code, at the end of development you still want one responsibility per-class (NOT per partial class). It's just a stepping-stone :)

查看更多
十年一品温如言
7楼-- · 2019-01-02 17:06
  1. Multiple Developer Using Partial Classes multiple developer can work on the same class easily.
  2. Code Generator Partial classes are mainly used by code generator to keep different concerns separate
  3. Partial Methods Using Partial Classes you can also define Partial methods as well where a developer can simply define the method and the other developer can implement that.
  4. Partial Method Declaration only Even the code get compiled with method declaration only and if the implementation of the method isn't present compiler can safely remove that piece of code and no compile time error will occur.

    To verify point 4. Just create a winform project and include this line after the Form1 Constructor and try to compile the code

    partial void Ontest(string s);
    

Here are some points to consider while implementing partial classes:-

  1. Use partial keyword in each part of partial class.
  2. The name of each part of partial class should be the same but the source file name for each part of partial class can be different.
  3. All parts of a partial class should be in the same namespace.
  4. Each part of a partial class should be in the same assembly or DLL, in other words you can't create a partial class in source files from a different class library project.
  5. Each part of a partial class must have the same accessibility. (i.e: private, public or protected)
  6. If you inherit a class or interface on a partial class then it is inherited by all parts of that partial class.
  7. If a part of a partial class is sealed then the entire class will be sealed.
  8. If a part of partial class is abstract then the entire class will be considered an abstract class.
查看更多
登录 后发表回答