Knowledge about packing and unpacking

Source: Internet
Author: User

Boxing ):Value Type-> reference type. To put a value type data on the stack, You need to pack the data.

Unboxing ):Reference Type-> value type. You need to unpack a value type data stored on the stack.

 

Value Type(Original Type (Sbyte,Byte,Short,Ushort,Int,Uint,Long,Ulong,Char,Float,Double,Bool,Decimal), Enumeration(Enum), Structure(Struct);

Value Type data is allocated to the stack.

Reference Type(Class, interface, array, Delegate, String, etc.); the referenced data is allocated to the stack.

 

For example, for the following simple packing and unpacking operation statements.

Int I = 123 ;
Object OBJ = I; // Boxing
If (OBJ Is Int )
Int J = ( Int ) OBJ; // Unboxing

The meaning of packing and unpacking: The value type is the data container, which is stored on the stack and does not have polymorphism.. NET Framework in the design of the entire object level, the system. object is the base class of all types, but obejct is the reference type, and the base class of value type is system. valuetype, which is from system. objects are derived, which leads to a conflict. packing and unpacking are to solve the difference between the two types.

A value type is put into a reference object of an untyped type, so that the value type can be applied to those scenarios where only the reference type can be used. A copy of the value type is extracted from the preceding packing object. Both packing and unpacking are time-consuming operations.

The packing operation converts the value type to a reference type. In this process, a new reference exclusive is created and allocated to the stack, A copy of the value type is stored in the reference object. When we need to obtain any information from the packing object, a copy of the value type will be created, and then it will be returned. The key is:When we need to reference a type, a new object of the reference type will be created and put into the heap; when we need to access the information of the packed object, A copy of the corresponding value type is created and returned.

The biggest problem with packing and unpacking is that they happen automatically. When we use the value type and expect the reference type, the compiler will automatically generate the packing and unpacking statements.

Let's take a look at the following statement, and the packing and unpacking operations have also taken place.

 

  Console. writeline ("A few numbers: {0}, {1}, {2}",
25,32,50);

AboveCodeThe reason for packing is that the parameter type required by the writeline method is system. object, while 25 is an int type and belongs to the value type. Therefore, it needs to be boxed. In the internal implementation of the writeline method, you need to call the tostring () method of the method parameter, in order to call the method of packing objects, the unpacking operation will occur.

 

To avoid packing and unpacking, you can modify the above Code as follows.

 

  Console. writeline ("A few numbers: {0}, {1}, {2}",
25. Tostring (),32. Tostring (),50. Tostring ());

In addition, because both packing and unpacking generate new instances, sometimes some strange bugs may occur. Let's look at the following code.

 

 

Code

  1   Public     Struct  Person
2 {
3 Private String _ Name;
4
5 Public String Name
6 {
7 Get
8 {
9 Return _ Name;
10 }
11 Set
12 {
13 _ Name = Value;
14 }
15 }
16
17 Public Override String Tostring ()
18 {
19 Return _ name;
20 }
21 }
22
23   // Using the person in a collection:
24 Arraylist attendees = New Arraylist ();
25 Person P = New Person ( " Old Name " );
26 Attendees. Add (P );
27
28 // Try to change the name:
29 // Wocould work if person was a reference type.
30 Person p2 = (Person) attendees [ 0 ]);
31 P2.name = " New name " ;
32
33 // Writes "old name ":
34 Console. writeline (
35 Attendees [ 0 ]. Tostring ());

In the above Code, person is a value type. When it is put into arraylist, it will be boxed. At this time, there will be a copy operation. When we need to obtain information about the person object in arraylist, A case is split and a copy operation is performed again. Therefore, when the objects in the arraylist are not modified, the replicas are modified.

 

We can modify the problems in the above Code in the following ways.

 

Code

  1   Public     Interface  Ipersonname
2 {
3 String Name
4 {
5 Get ; Set ;
6 }
7 }
8
9 Struct Person: ipersonname
10 {
11 Private String _ Name;
12
13 Public String Name
14 {
15 Get
16 {
17 Return _ Name;
18 }
19 Set
20 {
21 _ Name = Value;
22 }
23 }
24
25 Public Override String Tostring ()
26 {
27 Return _ Name;
28 }
29 }
30
31 // Using the person in a collection:
32 Arraylist attendees = New Arraylist ();
33 Person P = New Person ( " Old Name " );
34 Attendees. Add (P ); // Box
35
36 // Try to change the name:
37 // Use the interface, not the type.
38 // No Unbox needed
39 (Ipersonname) attendees [ 0 ]). Name = " New name " ;
40
41 // Writes "new name ":
42 Console. writeline (
43 Attendees [ 0 ]. Tostring ()); // Unbox
44
45

The reference type after packing implements all interfaces on the original value type object, which means no replication will happen again, but when we call ipersonname. when the name attribute is used, it will forward the call request to the value type inside the "box", and implement the interface on the value type so that we can access the inside of the "box, this allows you to directly change the information in the arraylist.

 

 

In short, we should convert any value type to system. object or interface type construction keeps a close eye on, for example, placing the value type into the set, and calling system on the value type. object-defined methods. All these operations convert the value type to system. object. We should avoid this conversion whenever possible.

 

Use the Microsoft ildasm.exe ToolDisassemblyProgram, You can clearly see the packing and unpacking.

 

 

 

 

 

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.