我想知道是否有人能给我一个概述,为什么我要使用它们,在这个过程中我能获得什么好处。
当前回答
下面列出了部分类的一些优点。
您可以分离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.
多个开发人员可以同时为类编写代码。
压缩大型类可以更好地维护应用程序。假设您有一个具有多个接口的类,因此您可以根据接口实现创建多个源文件。理解和维护源文件具有部分类的接口是很容易的。
其他回答
一个很好的用法是将生成的代码与属于同一类的手写代码分离。
例如,由于LINQ to SQL使用部分类,您可以编写自己的某些功能片段的实现(如多对多关系),并且当您重新生成代码时,这些自定义代码片段不会被覆盖。
WinForms代码也是如此。所有设计器生成的代码都放在一个文件中,您通常不会接触这个文件。手写的代码放到另一个文件中。这样,当您在设计器中更改某些内容时,您所做的更改不会被影响。
在处理大型类时,或在团队中工作时,尽可能保持所有内容的干净,您可以在不重写的情况下编辑(或始终提交更改)
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 https://web.archive.org/web/20211020111732/https://www.4guysfromrolla.com/articles/071509-1.aspx
另一个用途是分割不同接口的实现,例如:
partial class MyClass : IF3
{
// main implementation of MyClass
}
partial class MyClass : IF1
{
// implementation of IF1
}
partial class MyClass : IF2
{
// implementation of IF2
}
部分类最近帮助了源代码控制,多个开发人员在一个文件中添加新方法,并将其添加到文件的同一部分(由Resharper自动化)。
这些推入git会导致合并冲突。我发现没有办法告诉合并工具把新方法作为一个完整的代码块。
在这方面,部分类允许开发人员坚持他们文件的一个版本,并且我们可以稍后手工将它们合并回去。
的例子,
cs—保存字段、构造函数等 MainClass1.cs—开发人员实现时的新代码 cs -是另一个用于新代码的开发人员类。
推荐文章
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 在ASP中选择Tag Helper。NET Core MVC
- 如何在没有任何错误或警告的情况下找到构建失败的原因
- 跨线程操作无效:控件“textBox1”从创建它的线程以外的线程访问
- 否ConcurrentList<T>在。net 4.0?
- 在c#中解析字符串为日期时间