C # Structure

Source: Internet
Author: User

The structure is defined by the struct keyword. Similar to a class, it indicates the data structure that can contain data members and function members.
In general, we seldom use the structure, and many people do not recommend the structure, but. NET Framework is a basic architecture in general systems, so it is necessary to understand it.
Structural Features:
The structure is a value type and does not require heap allocation. Structure instantiation does not use the new operator.
In structure declaration, initialization fails unless the field is declared as const or static. Structure types are never abstract and always implicitly sealed. abstract and sealed modifiers are not allowed in structure declaration.
The default constructor (constructor without parameters) or destructor cannot be declared, but the constructor with parameters can be declared. The structure can implement interfaces, but it cannot inherit from another structure or class, and cannot be used as the base of a class. All structures are directly inherited from System. valueType, which is inherited from System. object. structure is copied when values are assigned. When a structure is assigned to a new variable, all data is copied, and any modifications made to the new copy do not change the data of the original copy. Remember this when using a set of value types (such as Dictionary <string, myStruct>. A variable of the structure type directly contains the data of this structure, while a variable of the class type only contains a reference to the corresponding data (the referenced data is called an "object "). However, the structure can still be passed to function members through ref and out parameter references. The structure can be null, so null values can be assigned to it. StructA
{Publicintx; // The publicinty value cannot be assigned directly; public static stringstr = null; // static variables can initialize publicA (intx, inty) // constructor with parameters {this. x = x; this. y = y; Console. writeLine ("x = {0}, y = {1}, str = {2}", x, y, str) ;}} classProgram {staticvoidMain (string [] args)
{A a = newA (1, 2); A a1 = a;. x = 10; Console. writeLine ("a1.x = {0}", a1.x); Console. read () ;}result: x = 1, y = 2, str =
A1.x = 1
At this time, the a1.x value is 1 because assigning a value to a1 is a copy of the value. Therefore, a1 is not subject to a. x value change.
However, if A is a class, then x in A and a1 references the same address, the a1.x value will output 10.
We know that the value of a class can be converted to the object type or the interface type implemented by the class, this requires that the corresponding reference be processed as another type during compilation.
Similarly, values of the object type or interface type can be converted back to the class type without changing the reference. Of course, in this case, you need to check the runtime type. Because the structure is not a reference type, the above operations are implemented in different ways for the structure type.
When the value of the structure type is converted to the object type or the interface type implemented by the structure, a packing operation is performed.
Otherwise, when the object type value or interface type value is converted back to the structure type, a box-breaking operation is executed.
Compared with the same operation on the class type, the main difference is:
The binning operation copies the related structure values to the boxed instances, and the unboxing operation re-creates a structure value from the boxed instances.
Therefore, after the binning or unboxing operation, changes to the structure outside the "binning" will not affect the boxed structure. StructProgram
{StaticvoidMain (string [] args)
{Inti = 1; objecto = I; // implicitly boxed I = 123; Console. writeLine ("I = {0}, o = {1}", I, o); Console. read () ;}// the result is: I = 123, o = 1 Structure and constructor. We know that the structure cannot use the default constructor, but only the constructor with parameters can be used, when defining a constructor with parameters, you must Initialize all fields in the structure. If initialization of all fields is not completed, an error occurs during compilation. Can a static constructor be used for a structure?
Yes. The static constructor of the structure follows the same rules as the static constructor of the class.
When will the static constructor of the structure be triggered? The instance Member of the structure is referenced, the static member of the structure is referenced, and the declared constructor of the structure is called. However, the default value of the created structure type does not trigger the static constructor.
Why cannot I customize a constructor with no parameters in the structure?
The constructor of the structure type is similar to the constructor of the class. It is used to initialize the member variables of the structure, but struct cannot contain the explicit default constructor,
Because the compiler automatically provides a constructor, this constructor initializes each field in the structure to the default value displayed in the default value table.
However, this default constructor is called only when the structure is instantiated with new. The default constructor called for the value type is not required.
StructA {staticA ()
{Console. WriteLine ("I am A.");} publicvoidFun ()
{}} ClassProgram {staticvoidMain (string [] args)
{A a = newA (); a. Fun (); // The instance Member of the structure is referenced by Console. Read () ;}the result is: I am.
Structure and inheritance:
A structure declaration can specify the list of Implemented interfaces, but cannot specify the base class.
Because the structure does not support inheritance of classes and structures, the declared Accessability of structure members cannot be protected or protectedinternal. the function member in the structure cannot be abstract or virtual, so the override modifier is only applicable to rewriting from System. valueType inheritance method.
To design a programming language without inheritance?
In fact, class inheritance costs a lot-because of inheritance, each class needs to use additional data space to store the "inheritance diagram" to represent the inheritance history of the class,
Generally speaking, it is our family tree, which stores the 18th generation of our ancestor. Only in this way can we know where we came from, genealogy must be stored in extra space.
Do not think that the space for storing the "inheritance map" is very small. If our program needs to use 10000 points to store the character form data in the game,
There are N more people in one scenario. The memory overhead is not a small amount. So we can save memory space by declaring a Point as a Struct instead of a class. InterfaceITest
{VoidFun (intx, inty);} structA: ITest {publicvoidFun (intx, inty) // methods in the implicit implementation interface {Console. writeLine ("x = {0}, y = {1}", x, y) ;}} classProgram {staticvoidMain (string [] args)
{A a; // The instantiation of the structure does not use new. fun (1, 2); Console. read ();} // The result is: x = 1, y = 2. Under what circumstances can the structure be instantiated without the use of new?
If there are no parameters in the structure, new can be used for structure instantiation. If there are parameters in the structure, all parameters in the structure must be initialized before new can be used for structure instantiation. When should I use the structure?
Struct structures are suitable for some small data structures. The data contained in these data structures is mainly data that is not modified after the structure is created;
For example, the struct type is suitable for lightweight objects such as Point, Rectangle, and Color.
Although a vertex can be expressed as a class, the structure is more effective in some cases.
If you declare an array consisting of 10000 Point objects, You need to allocate more memory to reference each object. In this case, you can use the structure to save resources.
Some object-oriented features are not used during definition;
The performance of the struct is much higher than that of the class type without the case of packing and unpacking.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.