Analysis of the characteristics of C # structure 2009-08-13 11:18 deviation of consciousness Baidu spacefont Size:T | T
What are the characteristics of C # struct? What is the difference between a C # struct and a class? This article will introduce you to the relevant content.
AD:
What are the characteristics of C # struct? Let's take a look at:
The struct type of a C # struct is a type of value that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an inventory item. The following example shows a simple struct declaration.
- Public struct PostalAddress
- {
- Fields, properties, methods and events go ...
- }
Structs share almost all the same syntax as classes, but structs are more restrictive than classes:
Although the static field of a struct can be initialized, the struct instance field declares or cannot use an initializer.
Structs cannot declare default constructors (constructors with no parameters) or destructors.
A copy of the structure of the C # struct is automatically created and destroyed by the compiler, so you do not need to use the default constructors and destructors. In effect, the compiler implements the default constructor by assigning default values to all fields (see Default Values Table). Structs cannot inherit from classes or other structures.
A struct is a value type--if you create an object from a struct and assign the object to a variable, the variable contains all the values of the structure. When you copy a variable that contains a structure, all data is copied, and any modifications you make to the new copy do not alter the old copy's data. Because structs do not use references, structs are not identified-two value type instances with the same data cannot be distinguished. All value types in C # are inherently inherited from ValueType, which inherits from object.
C # struct compilers can convert value types to reference types in a process called boxing.
The structure of C # struct has the following characteristics:
Structs are value types, and classes are reference types
When you pass a struct to a method, the structure is passed by value and is not passed as a reference.
Unlike classes, structs can be instantiated without using the new operator.
Structs can declare constructors, but they must take arguments
A struct cannot inherit from another struct or class and cannot be used as a base for a class. All structures are directly inherited from System.ValueType, which inherit from System.Object.
The structure of C # struct can implement interface.
Initializing an instance field in a struct is an error.
Analysis of the characteristics of C # structure body