introduction
In C#, loading and boxing is a necessary mechanism for different behaviors of coordinated values and reference types. However, their purpose and use cases may confuse programmers. This guide clarifies why these concepts are crucial and provide examples of practical applications.The importance of
boxing and boxingIncuffing and boxing allows C#to maintain a unified type system
, so that the value type and reference type can be consistently interacting and processed. Value types (such as SHORT and int) directly store their data in variables. Instead, the reference type references the underlying objects in other positions in the memory.In order to promote the seamless interaction between these different data structures, the box creates a packaging object, which contains the value type data so that it can be treated like a reference type. This allows it to easily store and operate the type of operation value in the data structure designed for reference type.
Application scenarios for boxing and boxing
A classic use case for packing is left by , which only accepts objects. These sets need to be packed to store the value type, as shown in the ArrayList example:
short s = 25; object objshort = s; // Packing In the era of
in modernshort s = 25;
object objshort = s; // 装箱
hidden conversion: The hidden conversion between the packet processing value type and the reference type, for example: ]
double e = 2.718281828459045; int EE = (int) e; // hidden conversion from Double to int (need to be packed)double e = 2.718281828459045;
int ee = (int)e; // 从double到int的隐式转换(需要装箱)
double e = 2.718281828459045;
object o = e; // 装箱
int ee = (int)(double)o; // 拆箱和显式转换
When installing the structure (value type), a copy will be created. Instead, when loading (reference type), a reference to the original object will be created. This behavior difference will affect the calculation results of the box installation value:
[struct | class] Point {...} Point p = new point (1, 1); object o = p; p.x = 2; Console.writeline ((((((((())))) .x); // Output: 1 (if it is a structure)/ 2 (if it is class)Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3