C#-value types and reference types

table of Contents

1. Concept

Two, data type

3. Comparison of the two

Fourth, the connection between the two

supplement:


1. Concept

Value type: store the value directly, store its value on the stack

Application type: store a reference to its value, store an address on the stack, store a value on the heap

Two, data type

3. Comparison of the two

 

Value type

Reference type

source

Inherited from System.ValueType

Inherited from System.Object

use

Represents actual data

Represents a pointer or reference to data stored in the memory heap

Data storage location

Stored in the memory stack

Stored in the heap of memory, and only the address of the object in the heap is stored in the memory unit

Variable storage type

Store the actual data directly

The address where the data is stored, that is, the reference of the object

Save location

The variable directly saves the value of the variable in the stack

Variables store the address of the actual data in the stack, and store the actual data in the heap

Inheritance

Sealed, can not be used as any other type of base class, single inheritance or multiple inheritance interface

Generally inherited

variable

Can not be Null, the value type will be automatically initialized to a value of 0

By default, it is created as a Null value, which means that it points to the reference address of any managed heap. Operations on a reference type with a value of Null will throw a NullReferenceException exception

Fourth, the connection between the two

Value types and reference types can be converted to each other, that is, boxing and unboxing operations:

Boxing occurs when a value type is converted to a reference type, and a data item (copy) is automatically copied from the stack to the heap.

int i = 8; 
object o = i;   // 装箱 // 首先在堆中开辟出一片区域,再将 i 的一个副本放在该区域中。 
                        // 所有引用都必须引用堆上的对象

Unboxing occurs when a reference type is converted to a value type, and a data item (copy) is automatically copied from the heap to the stack.

int i = 8; 
object o = i;   // 装箱 
i = (int)o;     // 拆箱 // 此处使用强制类型转换(cast)

supplement:

Managed heap: It is the basis of automatic memory management in CLR (Common Language Database). When a new process is initialized, a contiguous area of ​​address space is reserved for the process at runtime. This reserved address space is called the managed heap.

Guess you like

Origin blog.csdn.net/TGB_Tom/article/details/109329224