Packing (Boxing) and unboxing (Unboxing)

Object is a reference type, but its subclasses Int32 not even able to go to Object "requirement must be a reference type." 

Place, in violation of the principle of inheritance, so it is necessary to Int32 installed in Object to pass.

Packing: Type interface conversion from a value to a reference type.

Unboxing: conversion value from a reference type to type.  

            object obj = null; // reference type

            obj = 1; // packing, Boxing . The value of the package type is a reference type.

            int i1 = (int) obj; // unpacking. unboxing

 

2) The following three code has nothing wrong with inboxing or unboxing, for example, to explain how memory is changed

int i=10;

object obj = i;

int j = obj;

 

Analysis: when inboxing (packing) is no explicit type conversions, but Unboxing (unpacking) require explicit type conversions, the third line should read:

3 int j = (int)obj;    

To grasp the boxing and unboxing, we must understand the CTS and its features:

    NET and one of the important technical foundation CTS (Common Type System). CTS is to achieve a common type system in the application statement and rules that must be followed when using these types exist. .Net the type of the system is divided into two categories: value types and reference types.

Everything is an object of the CTS; all objects are derived from a base class --System.Object type. A value of type biggest feature is that they can not have a total value is null, the value of a variable of type. In order to address the type of value is not null, null reference types can be a problem, Microsoft introduced .Net in the boxing and unboxing: boxed value type is a reference type packaging them into a reference type; and from a reference type get value type unpacking be packaged .

(*)

 

object.ReferenceEquals (); // used to determine whether two objects are the same object

Console.WriteLine (object.ReferenceEquals (3,3)); // because two 3 is mounted to the two boxes, it is false

Relationship of Equals ==

Guess you like

Origin www.cnblogs.com/boke1/p/11056669.html