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 17:13

Whenever I have a class that contains a nested class that is of any significant size/complexity, I mark the class as partial and put the nested class in a separate file. I name the file containing the nested class using the rule: [class name].[nested class name].cs.

The following MSDN blog explains using partial classes with nested classes for maintainability: http://blogs.msdn.com/b/marcelolr/archive/2009/04/13/using-partial-classes-with-nested-classes-for-maintainability.aspx

查看更多
栀子花@的思念
3楼-- · 2019-01-02 17:13

Partial classes are primarily introduced to help Code generators, so we (users) don't end up loosing all our work / changes to the generated classes like ASP.NET's .designer.cs class each time we regenerate, almost all new tools that generate code LINQ, EntityFrameworks, ASP.NET use partial classes for generated code, so we can safely add or alter logic of these generated codes taking advantage of Partial classes and methods, but be very carefully before you add stuff to the generated code using Partial classes its easier if we break the build but worst if we introduce runtime errors. For more details check this http://www.4guysfromrolla.com/articles/071509-1.aspx

查看更多
长期被迫恋爱
4楼-- · 2019-01-02 17:16

Another use is to split the implementation of different interfaces, e.g:

partial class MyClass : IF1, IF2, IF3
{
    // main implementation of MyClass
}


partial class MyClass
{
    // implementation of IF1
}

partial class MyClass
{
    // implementation of IF2
}
查看更多
登录 后发表回答