[C # tips] binning and unboxing value types

Source: Internet
Author: User

Freesc Huang @ HUST All Rights Reserved
2008-2-11

Keywords
. NET Framework, C #, value type, packing, unpacking, CLR

Body
Half a year ago, I wrote a short article about the Value Type Packing question (here). Now, it seems that some things were not completely explained at the time. I took an example here to talk about it. Understand these problems, for a. netProgramIt is very helpful for us to understand Clr and write efficient programs. As for what is the value type and what is the box & Unbox, I will not repeat it here. Let's take a look at the following short lines.Code:

Code
1 Internal   Struct Ticket
2 {
3 Private String _ start, _ terminal; // Start and end
4 Private Int32 _ distance; // Distance
5
6 Public Ticket ( String Start, String Terminal, int32 distance)
7 {< br> 8 _ start = Start;
9 _ terminal = terminal;
10 _ distance = distance;
11 }
12 /**/ ///   <Summary>
13 /// Rebook tickets
14 ///   </Summary>
15 ///   <Param name = "newterminal"> New Terminal </Param>
16 ///   <Param name = "newdistance"> Distance to the terminal </Param>
17 Public   Void Rebook (string newterminal, int32 newdistance)
18 {
19_ Terminal=Newterminal;
20_ Distance=Newdistance;
21}
22 /**/ /// <Summary>
23///Override the tostring method of system. valuetype
24/// </Summary>
25 Public   Override String tostring ()
26 {
27 Return String. Format ( " From {0} to {1}, {2} km " ,
28 _ Start,
29 _ Terminal,
30 _ Distance ); // Inside the method, _ distance is packed
31 }
32 }
33
34   Public   Sealed   Class Program
35 {
36 Public   Static   Void Main ()
37 {
38 Ticket t =   New Ticket ( " Beijing " , " Hankou " , 1225 );
39 // Value Type instance t is packed here for the first time: ticket --> Object --> override tostring
40 Console. writeline (t );
41
42 // Display packing
43 // Console. writeline (object) T). tostring ());
44
45 T. rebook ( " Shanghai " , 1400 );
46 Console. writeline (t );
47
48 Object o = T;
49 Console. writeline (O );
50
51 (Ticket) O). rebook ( " Guangzhou " , 2000 );
52 Console. writeline (O );
53 }
54 }

The program is very short and simple. It defines the structure of a train ticket (ticket). It only includes the start point, end point, and mileage. It is a value type (the structure is derived from system. valuetype ). We mainly focus on the output of this train ticket.

First, create a train ticket instance t (38th rows), initialize it to Beijing to Hankou, 1225 kilometers, and then call the console for the first time. writeline, because the console. writeline () does not have a overload whose parameter is ticket. here t is packed (as mentioned here), and this "boxed" ticket (referred to as tii) the CLR defaults to an object and calls tostring () on the tii of this object instance (), at this time, the CLR found in the boxed ticket method table that this type overwrites the tostring () method, it will call this method implicitly so that we can see "from Beijing to Hankou, 1225 ". Maybe the code I commented out will help you better understand this process.

Then, on that value type T (rather than tii), call rebook and change it to Shanghai, 1400 km. Then call writeline. After the same process as above, we can get the output "from Beijing to Shanghai, 1400 km ".

Then, we explicitly pack T. In fact, the two lines of code (lines 48, 49) are the same as the Code commented out by line 43rd, writeline () the method itself has an object overload parameter. So we can still get "from Beijing to Shanghai, 1400" as expected ".

Next, this sentence is interesting. We split the tii pointed to by O, copied the corresponding fields to the value type instance tiII on the stack, and then called the rebook Method for tiII, change it from Beijing to Guangzhou. Note that the modification here is made directly on the stack. It has nothing to do with the O on the hosting stack, so at this time we call eaglewriteline (o); the output is still "from Beijing to Shanghai, 1400 km ".

To prevent tiII from being spam outside of our control, we asked rebook to immediately return this tiII to us, copy it to an instance named T2, and output it, in this way, we get the modified final result "from Beijing to Guangzhou, 2000 km ".
The program output is as follows:

The program code is here
This article counts as a supplement and extension to the previous article. It is also hoped that this example will give you a better understanding of the principle of Value Type Packing and the behavior of CLR behind it, it's easy for people. Welcome to the discussion :-)

 

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.