简体   繁体   English

为什么Windows窗体应用程序中的窗体类被声明为部分?

[英]Why the form class in windows form application is declared as partial?

  1. Can somebody tell why and for what it is declared as partial? 有人可以告诉为什么以及它被宣布为部分?
  2. what is its use? 有什么用?
  3. Is this possible to declare it without partial? 这是否可以在没有偏见的情况下声明它?

It's declared partial because VS.NET will put "designer" code into a seperate .cs file that is actually, at compile time, part of the same class. 它被声明为部分,因为VS.NET会将“设计器”代码放入一个单独的.cs文件中,该文件实际上是在编译时属于同一个类的一部分。

If you have a Form1.cs you should also have a Form1.Designer.cs on the file system as well. 如果你有一个Form1.cs,你也应该在文件系统上有一个Form1.Designer.cs。 When you drop controls onto a form VS.NET will add code into that designer file. 当您将控件放到表单上时,VS.NET会将代码添加到该设计器文件中。 It's seperate because you don't want to see or touch that code, and don't want it getting in the way of your own code. 它是独立的,因为您不希望看到或触摸该代码,也不希望它妨碍您自己的代码。

So, the partial class feature in C# is mainly there to allow the seperation of your code and designer code. 因此,C#中的部分类功能主要用于分离代码和设计器代码。 At compile time the two (or more) files making up the partial class become a single class - at runtime there isn't any difference between a class defined as partial and one that isn't. 在编译时,构成分部类的两个(或更多)文件成为单个类 - 在运行时,定义为partial的类与不定义的类之间没有任何区别。

"Back in the day" before partial existed all the designer code was lumped in with your own, and this made for messy .cs files and the possibility of developers changing code that VS.NET was expecting to have exclusive rights to. 部分存在之前的“回到当天”所有的设计师代码都与你自己的代码混在一起,这使得凌乱的.cs文件和开发人员改变VS.NET期望拥有专有权的代码的可能性。 So, a Form will work fine (if written without designer support) without being partial (eg if you were generating the entire file yourself from a T4 template). 因此,表单可以正常工作(如果没有设计人员的支持),而不是部分(例如,如果您自己从T4模板生成整个文件)。

Why would you want to remove the "partial"? 你为什么要删除“部分”?

It's declared partial because the class is defined in two files. 它被声明为partial,因为该类是在两个文件中定义的。 Whenever you want to split up a class's definition into several files, you can use the keyword partial . 只要您想将类的定义拆分为多个文件,就可以使用关键字partial

The form design has its code in a different .cs file and its events and other code (that you code in) is stored in a different .cs file. 表单设计将其代码放在不同的.cs文件中,其事件和其他代码(您编写的代码)存储在不同的.cs文件中。 But both the file is declared using the same class name, ie the name of your form. 但是这两个文件都使用相同的类名声明,即表单的名称。 Thats why this is marked as "partial". 这就是为什么这被标记为“部分”。 This holds also true for ASP.NET pages, if you use code-behind. 如果您使用代码隐藏,那么对于ASP.NET页面也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM