当前位置:网站首页>C - partial keyword
C - partial keyword
2022-07-24 15:22:00 【wumingxiaoyao】
C# partial keyword
introduction
partial Keyword is used to split a class 、 A structure 、 The definition of an interface or a method into two or more files . Each source file contains a part of the type or method definition , When you compile an application, you put all the parts together . In the design Framework when , Can be fully utilized partial This feature .
Division class
Under what circumstances do you need to split class definitions ?
- When dealing with large projects , Making a class distributed in multiple independent files allows multiple programmers to process the class at the same time .
- When using automatically generated source files , You can add code without having to recreate the source file . Visual Studio Creating Windows forms 、Web This method is used when the service wrapper code, etc . You can create code that uses these classes , In this way, there is no need to modify Visual Studio Generated files .
- When using the source generator to generate additional functions in a class .
Example
take Coords class The division is in 2 Defined in files .
CoordsOne.cs
Defined Coords Class constructor
Pay attention to the signature partial class Coords
namespace ConsoleApp1.PartialClass
{
public partial class Coords
{
private int x;
private int y;
public Coords(int x, int y)
{
this.x = x;
this.y = y;
}
}
}
CoordsTwo.cs
Defined Coords class
Pay attention to the signature partial class Coords
namespace ConsoleApp1.PartialClass
{
public partial class Coords
{
public void PrintCoords()
{
Console.WriteLine("Coords: {0},{1}", x, y);
}
}
}
TestPartial.cs
Test the above partial classes
using ConsoleApp1.PartialClass;
namespace ConsoleApp1
{
internal class TestPartial
{
static void Main(string[] args)
{
Coords coords = new Coords(10, 20);
coords.PrintCoords();
}
}
}
result :
Coords: 10,20
partial Segment restrictions
The following rules should be followed when dealing with partial class definitions :
- All partial type definitions to be parts of the same type must use
partialTo embellish .
for example , The following class declaration generates an error :
public partial class A {
}
//public class A { } // Error, must also be marked partial
partialModifiers can only appear next to keywordsclass、structorinterfaceFront position .Nested partial types are allowed in partial type definitions , As shown in the following example :
partial class ClassWithNestedClass
{
partial class NestedClass {
}
}
partial class ClassWithNestedClass
{
partial class NestedClass {
}
}
All partition type definitions the first mock exam must be in the same assembly and the same module. (.exe or .dll file ) Defined in . A partial definition cannot span more than one module .
After testing, the files of these parts must be in the same namespace.
Or the example above ,CoordsThree.cs It's also defined aspartialclass , however comparison CoordsOne.cs and CoordsTwo.cs Not in the same namespace , Will make mistakes .

The class name and generic type parameters must match in all partial type definitions . Generic types can be partial . Each partial declaration must use the same parameter names in the same order .
If a keyword appears in a partial type definition , The keyword cannot conflict with the keyword specified in other partial definitions of the same type :public,private,protected,internal,abstract,sealed etc.
take CoordsOne.cs in public Change to internal, Generate access attribute conflict .
Divisional interface and structure
Empathy , You can also develop partial structures and interfaces
partial interface ITest
{
void Interface_Test();
}
partial interface ITest
{
void Interface_Test2();
}
partial struct S1
{
void Struct_Test() {
}
}
partial struct S1
{
void Struct_Test2() {
}
}
Partial methods
A partial method defines a signature in part of a partial type , And the implementation is defined in another part of this type . Through the partial method , Class designer can provide method hooks similar to event handlers , So that developers can decide whether to implement . If the developer does not provide an implementation , Then the compiler deletes the signature at compile time . The following conditions apply to the partial method :
The declaration must contain the following keywords
partialstart .The signatures in the parts of a partial type must match .
Constructors 、 finalizers 、 Overload operator 、 It is not allowed to use
partialkeyword .
for example :
namespace PM
{
partial class A
{
partial void OnSomethingHappened(string s);
}
// This part can be in a separate file.
partial class A
{
// Comment out this method and the program
// will still compile.
partial void OnSomethingHappened(String s)
{
Console.WriteLine("Something happened: {0}", s);
}
}
}
In the following cases , You don't need to use a partial method to achieve :
- There are no accessibility modifiers ( Include default special ).
- return void.
- There are no output parameters .
- There are no modifiers below :virtual、override、sealed、new or extern.
this and partial The difference between
C# - this Usage of There is an introduction to this It has the function of extending class methods , that this and partial The difference is ?
- The difference in concept ,
thisIt is to expand the original function ,partialIt is to divide the whole into several parts for storage , Easy to maintain . - The difference in implementation
patialThe signature of the branch shall be consistent , Must bepartialclass/interface/struct Name, The file names are different .
this The extension class name is different , But it must be a static class , Static method , The first parameter of the method must bethisClassName - The difference between calls
partialAll documents of the division must be in the same namespace NamespacethisExtensions can be in different namespaces , But you need to import extended namespace Namespace before calling the extended method .
边栏推荐
- Sword finger offer II 001. integer division
- 华为无线设备配置WPA2-802.1X-AES安全策略
- 2022 RoboCom 世界机器人开发者大赛-本科组(省赛) CAIP 完整版题解
- Spark: get the access volume of each time period in the log (entry level - simple implementation)
- 2022 robocom world robot developer competition - undergraduate group (provincial competition) -- question 2: intelligent medication assistant (finished)
- 文件操作详解
- 遭受DDoS时,高防IP和高防CDN的选择
- MongoDB入门学习
- Performance test - analyze requirements
- [machine learning basics] - another perspective to explain SVM
猜你喜欢

Jmeter-调用上传文件或图片接口

25. From disk to file

Activity Registration: how to quickly start the open source tapdata live data platform on a zero basis?
![Property datasource is required exception handling [idea]](/img/f3/50d36ed9445695c02e2bd622109d66.png)
Property datasource is required exception handling [idea]

打假Yolov7的精度,不是所有的论文都是真实可信

VAE(变分自编码器)的一些难点分析

什么是防火墙?防火墙能发挥什么样的作用?
![[quantitative test]](/img/df/f2d8b252169213af340f3e535bddef.png)
[quantitative test]

Existence form and legitimacy of real data in C language (floating point number)

Leetcode-09 (next rank + happy number + full rank)
随机推荐
Preparation of mobile end test cases
pytorch with torch.no_ grad
Is it safe for Huatai Securities to open a mobile account and will it be leaked
异或程序
Simple encapsulation of wechat applet wx.request
维护香港服务器安全的9个关键措施
Summary of feature selection: filtered, wrapped, embedded
2022 RoboCom 世界机器人开发者大赛-本科组(省赛)RC-u4 攻略分队 (已完结)
[USENIX atc'22] an efficient distributed training framework whale that supports the super large-scale model of heterogeneous GPU clusters
2022 RoboCom 世界机器人开发者大赛-本科组(省赛) CAIP 完整版题解
力扣 31.下一个排列--双指针法
Storage and traversal of Graphs
Unity 使用NVIDIA FleX for Unity插件实现制作软体、水流流体、布料等效果学习教程
DS graph - minimum spanning tree
C# SQLite Database Locked exception
2022 robocom world robot developer competition - undergraduate group (provincial competition) -- question 1: don't waste gold (finished)
Chiitoitsu
2022 robocom world robot developer competition - undergraduate group (provincial competition) rc-u4 strategy team (completed)
2022 RoboCom 世界机器人开发者大赛-本科组(省赛)---第一题 不要浪费金币 (已完结)
DS inner row heap sort