1. What is a local type?
C# 2.0
The concept of local types is introduced. Local types allow us to divide a class, structure or interface into several parts and implement them in several different .cs files.
Local types are suitable for the following situations:
(1)
The type is extremely large and should not be implemented in one file.
(2) Part of the code in a type is code generated by automated tools and should not be mixed with code written by ourselves.
(3)
Multiple people need to work together to write a class.
Local types are a pure language layer compilation process that does not affect any execution mechanism - in fact, the C# compiler will still merge the local types of each part into a complete class during compilation.
public partial class Program
{
static void Main(string[] args)
{
}
}
partial
class Program
{
public void Test()
}
(1)
Local types are only applicable to classes, interfaces, and structures. Delegates and enumerations are not supported.
(2) Each part of the same type must have the modifier partial.
(3)
When using partial types, the parts of a type must be in the same namespace.
(4) All parts of a type must be compiled at the same time.
3.
Points to note about partial types
(1) The keyword partial is a contextual keyword and can only be used with class, struct, and interface
Keywords have meaning only when they are put together. Therefore, the introduction of partial will not affect variables named partial in existing code.
(2)
The various parts of local types are usually placed in several different .cs files, but the C# compiler allows us to put them in the same file.
4.
Application properties of local types
Properties on local types have a "cumulative" effect.
[Attribute1, Attribute2("Hello")]
[Attribute3, Attribute2("Exit")]
partial class
Class1{}
[Attribute1, Attribute2("Hello"), Attribute3,
Attribute2("Exit")]
5.
Modifiers on local types
(1) Access modifiers on various parts of a type must maintain consistency.
(2) If a partial class uses the abstract modifier, the entire class will be considered an abstract class.
(3) If a partial class uses the sealed modifier, the entire class will be considered a sealed class.
(4)
Parts of a class cannot use contradictory modifiers. For example, you cannot use abstract on one part and sealed on another part.
(5) If a partial class uses the static modifier, the entire class will be considered a static class.
(1)
The base class specified on each part of a type must be consistent. A section may not specify a base class, but if specified, it must be the same.
(2) Interfaces on local types have a "cumulative" effect.
partial class Class2: Iinterface1, Iinterface2
{}
partial class Class2: Iinterface2
{}
class Class2: Iinterface1, Iinterface2, Iinterface3
{}
If you want more related articles, please pay attention to the PHP Chinese website (m.sbmmt.com)!