Sometimes the class and structure are unclear. When will classes be used? When should I use the structure?
Class, reference type
Structure, Value Type
Class: fields (except the const field) should always be private and encapsulated by public attributes;
1 ResponseCassetteCounter cassetteCounter = new ResponseCassetteCounter();
Structure: The new operator can be used like a class, but the heap memory is not allocated to the structure. After declaration, fields can be assigned directly; the compiler always provides a default constructor without parameters, which cannot be replaced; the structure does not support implementation inheritance, but supports interface inheritance;
1 Dimensions point = new Dimensions();2 point.Length = 3;3 point.width = 6;
1 Dimensions point;2 point.Length = 3;3 point.Width = 6;
If the class is defined in the second method, a compilation error occurs because the point contains an uninitialized reference;
Classes are stored in the heap. This method can be used to achieve great flexibility in the Data lifetime, but the performance may be compromised. Because of the optimization of the managed heap, this performance loss is relatively small; sometimes only a small data structure is required. At this time, the class provides more functions than we need, because of the Performance
The reason, it is best to use the structure. For memory allocation, the structure is faster than the class, but the structure is passed as a parameter or a structure is given to another structure (for example, a = B, where A and B are structures ), all contents of the structure are copied, and only references are copied for classes. This
There will be performance loss, depending on the size of the structure, the performance loss is also different;
When the structure is passed as a parameter to the method, It should be passed as a ref parameter to avoid performance loss; at this time, only the address of the structure in the memory is passed, in this way, the transfer speed is faster than the transfer speed in the class;
Do not use a non-parameter constructor in the C # structure. The default constructor initializes All numeric fields to 0 and the reference type fields to null, which are always provided implicitly, this is true even if other constructors with parameters are provided. The initial values of the provided fields cannot bypass the Default Construction.
Function, for example, the following code cannot pass during compilation
1 struct Dimensions2 {3 pub1ic double Length = 1; // error. Initial values not allowed4 pub1ic double Width = 2;// error. Initial values not allowed5 }
Of course, if dimensions is declared as a class, there will be no compilation errors in this Code;
Class and Structure