Partial Class is introduced in C #2.0, and Partial Method is introduced in C #3.0. These two syntax features share the same characteristics) the method code is scattered in multiple places.
1. features and applications of the Division class
1.1 division class definition
When defining a class, add the partial keyword. This class becomes a partial class.
The Division class allows the code of a class to be dispersed in more than one source code file.
The Person. cs code is as follows:
Copy codeThe Code is as follows: namespace PartialClassDemo1
{
Public partial class Person
{
Private int age;
Person (int age, string name)
{
This. age = age;
This. name = name;
}
Public int Age
{
Get
{
Return age;
}
Set
{
If (age <0 | age> 120)
Console. WriteLine ("invalid age ");
Else
This. age = Age;
}
}
Static void Main (string [] args)
{
Person p = new Person (19, "James ");
Console. WriteLine (p. Age );
Console. ReadKey ();
}
}
}
The code for Person2.cs is as follows:
Copy codeThe Code is as follows: namespace PartialClassDemo1
{
Public partial class Person
{
Private string name;
}
}
Note the following principles when using segmented classes:
(1) All classes that require "merge" must be declared with the partial keyword.
(2) All classes to be "merged" must be in the same project.
2. Why should I introduce a division class?
The segmented class is mainly used to isolate source code with different functions or types.
In addition, the distribution features can also be applied to the device structure and interfaces.
3. features and applications of the Distribution Method
The distribution method allows method declaration and method implementation code to be distributed in different files. Similar to the partial class, use the partial keyword to define the partial method.
Copy codeThe Code is as follows: partial void show (string str );
Partial void show (string str)
{
Console. WriteLine (str + "goodbye ");
}
The distribution method cannot have access modifiers or virtual, abstract, override new sealed, or extern modifiers.
The partial modifier can only appear next to the class struct interface void.
When the division method does not implement the code, the C # compiler will delete its call statement during compilation.
Now we know that the division method has this feature, but what is its use?
Using the division method allows us to insert a method placeholder in a common method to support writing methods that can add features at any time.
The division method cannot have multiple implementations.