我想知道是否有人能给我一个概述,为什么我要使用它们,在这个过程中我能获得什么好处。


当前回答

从MSDN:

1.在编译时,合并部分类型定义的属性。例如,考虑以下声明:

[SerializableAttribute]
partial class Moon { }

[ObsoleteAttribute]
partial class Moon { }

它们等价于以下声明:

[SerializableAttribute]
[ObsoleteAttribute]
class Moon { }

以下是所有部分类型定义的合并:

XML注释 接口 泛型类型参数属性 类属性 成员

2.另外,嵌套的分部类也可以是分部类:

partial class ClassWithNestedClass
{
    partial class NestedClass { }
}

partial class ClassWithNestedClass
{
    partial class NestedClass { }
}

其他回答

的确,Partial Class用于自动代码生成,其中一个用途是维护一个可能有上千行代码的大型类文件。你永远不知道你的类最终会有1万行,你不想用不同的名字创建一个新类。

public partial class Product
{
    // 50 business logic embedded in methods and properties..
}

public partial class Product
{
    // another 50 business logic embedded in methods and properties..
}
//finally compile with product.class file.

另一个可能的用途是多个开发人员可以使用同一个类,因为它们存储在不同的地方。人们可能会笑,但你永远不知道有时候情况会很棘手。

Product1.cs

public partial class Product
{
    //you are writing the business logic for fast moving product
}

Product2.cs

public partial class Product
{
    // Another developer writing some business logic...
}

希望这是有意义的!

我看到的另一个用法是,

扩展一个关于数据访问逻辑的大型抽象类,

我有各种文件的名字Post.cs,Comment.cs,Pages.cs…

in Post.cs 

public partial class XMLDAO :BigAbstractClass
{
// CRUD methods of post..
}


in Comment.cs 

public partial class XMLDAO :BigAbstractClass
{
// CRUD methods of comment..
}

in Pages.cs 

public partial class XMLDAO :BigAbstractClass
{
// CRUD methods of Pages..
}

分部类的主要用途是生成代码。如果你看看WPF (Windows Presentation Foundation)网络,你用标记(XML)定义你的UI。该标记被编译成部分类。您可以用自己的部分类填充代码。

下面列出了部分类的一些优点。

您可以分离UI设计代码和业务逻辑代码,以便易于阅读和理解。例如,你正在使用Visual Studio开发一个web应用程序,并添加一个新的web表单,然后有两个源文件,“aspx.cs”和“aspx.designer.cs”。这两个文件具有具有partial关键字的相同类。".aspx.cs"类有业务逻辑代码,而"aspx.designer.cs"有用户界面控件定义。

When working with automatically generated source, the code can be added to the class without having to recreate the source file. For example you are working with LINQ to SQL and create a DBML file. Now when you drag and drop a table it creates a partial class in designer.cs and all table columns have properties in the class. You need more columns in this table to bind on the UI grid but you don't want to add a new column to the database table so you can create a separate source file for this class that has a new property for that column and it will be a partial class. So that does affect the mapping between database table and DBML entity but you can easily get an extra field. It means you can write the code on your own without messing with the system generated code.

多个开发人员可以同时为类编写代码。

压缩大型类可以更好地维护应用程序。假设您有一个具有多个接口的类,因此您可以根据接口实现创建多个源文件。理解和维护源文件具有部分类的接口是很容易的。

作为预编译器指令的替代方案。

如果您使用预编译器指令(即# If DEBUG),那么您最终会看到一些看起来粗糙的代码与实际的Release代码混合在一起。

你可以创建一个单独的分部类来包含这些代码,或者将整个分部类包装在一个指令中,或者省略该代码文件,使其不被发送给编译器(实际上是做同样的事情)。