1. What is Union type Data Union (union) is a special class in which data members in a union are stored in memory that overlap each other. Each data member starts at the same memory address. The number of stores allocated to the Union is the amount of memory required to include its largest data member. Only one member can be assigned to a value at the same time.
Expression of union type data in C + +
Union tokenvalue{ char _cval; int _ival; Double _dval;};
View Code
Memory usage for 2.Union type data the allocation of the Union type data is based on the largest member variable, which means that the above union memory size is sizeof (double) =8
3. In C #, to specify the memory layout of members, we need to use the StructLayoutAttribute attribute together with the LayoutKind enumeration and FieldOffsetAttribute attributes. They are all located in the System.Runtime.InteropServices namespace.
C # simulates union type data in C + +
[StructLayout (Layoutkind.explicit, size=8)] struct tokenvalue{ [FieldOffset (0)] publicChar _cval; [FieldOffset (0)] Public int _ival; [FieldOffset (0)] Public Double _dval;}
View Code
We know that each data member of the union starts at the same memory address, and by applying [FieldOffset (0)] to each member of the Tokenvalue, we specify that the members are in the same starting position. Of course, we have to tell you beforehand. NET these members of the memory layout by us to the Lord, The LAYOUTKIND.EXPLICIT enumeration is passed to the constructor of the StructLayoutAttribute attribute and applied to the tokenvalue,.net to no longer interfere with the layout of the members of the struct in memory. In addition, I explicitly set the size of the Tokenvalue to 8 bytes, of course, this is optional.
Lock Use Note: 1.lock do not apply on the public type of data, such as lock (this) 2.lock do not apply on the string. NET all contents of the same string in the program domain, is the same instance 3.lock cannot lock an empty object
C # implements union and lock usage