-
-
Structure example
Public struct person
{
String name;
Int height;
Int weight
Public bool overweight ()
{
// Implement something
} S
}
Class Example
Public class testtime
{
Int hours;
Int minutes;
Int seconds;
Public void passtime ()
{
// Implementation of behavior
}
}
Call Process
Public class test
{
Public static Ovid main
{
Person myperson = new person // declaration Structure
Testtime mytime = new testtime // Declaration class
}
}
From the above example, we can see that the declaration of the class and the declaration of the structure are very similar, but the difference between struct and class is after the qualifier, and when used, similar methods are used to define new structures and new classes. What are the specific differences between classes and structures?
Differences between classes and structures
Value Type and reference type
Structure
The structure is a value type, and the value type is allocated to the stack. All base types are structure types. For example, int corresponds to system. int32 structure. String corresponds to system. string Structure. You can create more value types by using the structure.
Class
Class is the reference type, and the reference type is allocated on the stack.
The execution efficiency of stacks is higher than the execution efficiency of stacks. However, the stack resources are limited and it is not suitable for processing large logical and complex objects. Therefore, structure processing is a small object treated as a base type, and classes process a business logic.
Because the structure is a value type, you can create a new structure by assigning values between structures. Classes are reference types, and assigning values between classes is just copying references.
Note:
Although the structure and class types are different, their base types are all objects, and all types of base types in C # Are objects.
-
Although the new operator is used for structure initialization, the structure object is still allocated on the stack instead of the stack. If the new operator is not used, before all fields are initialized, the field remains unassigned and the object is unavailable.
-
-
Inheritance
Structure
It cannot be inherited from another structure or class. Although the structure is not explicitly declared using sealed, the structure is implicit sealed.
Class
Fully scalable. Unless the declared sealed is displayed, the class can inherit other classes and interfaces, and its own can also be inherited.
Note:
Although the structure cannot be inherited, the structure can inherit interfaces. methods are the same as class inheritance interfaces.
Example: structure implementation Interface
Interface iimage
{
Void paint ();
}
Struct picture: iimage
{
Public void paint ()
{
// Painting code goes here
}
Private int x, y, z;
// Other struct members
}