Note
(1)Structs do not support inheritance(继承).
(2)There are some differences in the way constructors work for structs. If you do not supply a default constructor, the compiler automatically creates one and initializes the members to its default values.
(3)Structs are really intended to group data items together.
(4)对于Structs是可以的
Dimensions point;
point.Length = 3;
point.Width = 6;
(5)对于Class上述是不可以的,只可如下:
var point = new Dimensions();
point.Length = 3;
point.Width = 6;
原因:Because point would contain an uninitialized reference—an address that points nowhere, so you could not start setting values to its fields. For a struct, however, the variable declaration actually allocates space on the stack for the entire struct, so it’s ready to assign values to.
(6)Positive and Negative:
1)On the positive side, allocating memory for structs is very fast because this takes place inline or on the stack. The same is true when they go out of scope. Structs are cleaned up quickly and don’t need to wait on garbage collection.
2)On the negative side, whenever you pass a struct as a parameter or assign a struct to another struct (as in A = B, where A and B are structs), the full contents of the struct are copied, whereas for a class only the reference is copied. This results in a performance loss that varies according to the size of the struct, emphasizing the fact that structs are really intended for small data structures.
readonly structs(C# 7.2)
It contains only a constructor that changes its members. The properties only contain a get accessor, thus change is not possible.
ref struct(C# 7.2)
Values only were stored in the stack.
Positive:Garbage collection could be reduced.
网友评论