C#值类型与引用类型

数据有值类型与引用类型,我们通常把引用类型的常量叫做实例

一、常量存储位置不同:
值类型常量在栈中,实例在托管堆中。

二、变量与常量的对应关系不同:
值类型变量的独立性:常量本身保存在变量自带的存储空间里,一个变量对应一个常量。
引用类型变量与实例的多对一关系:变量只保存常量所在的地址,同一个实例可以被多个变量引用。

三、初始化变量时内部操作不同:

1.初始化值类型变量
当给一个值类型变量赋值,会复制常量,放入变量中。

2.初始化引用变量
当给一个引用类型变量赋值,变量中存储的是实例的地址。
3.装箱
若用一个值类型常量给一个引用类型变量赋值,CLR尝试根据该常量,包装一个实例,再把该实例地址放到变量中。

int a=5;
Object o=a;//装箱,根据5被包装一个引用类型常量,用o保存对象地址。

装箱的应用实例(来自《CLR via C# 》):
if you know that the code that you’re writing is going to cause the compiler to box a single value type repeatedly, your code will be smaller and faster if you manually box the value type. Here’s an example:
using System; 

public sealed class Program 
{ 
    public static void Main() 
       {        
                Int32 v = 5;   // Create an unboxed value type variable. 

                #if INEFFICIENT        // When compiling the following line, v is boxed 
                                             // three times, wasting time and memory.              
                                            Console.WriteLine("{0}, {1}, {2}", v, v, v); 
                #else          // The lines below have the same result, execute   
                               // much faster, and use less memory.     
                             Object o = v;  // Manually box v (just once).  
                               // No boxing occurs to compile the following line.  
                              Console.WriteLine("{0}, {1}, {2}", o, o, o); 
            #endif    
    }  
} 
 If this code is compiled with the INEFFICIENT symbol defined, the compiler will generate code to box v three times, causing three objects to be allocated from the heap! This is extremely wasteful since each object will have exactly the same contents: 5. If the code is compiled without the INEFFICIENT symbol defined, v is boxed just once, so only one object is allocated from the heap. Then, in the call to Console.WriteLine, the reference to the single boxed object is passed three times. This second version executes much faster and allocates less memory from the heap. 

总结:为了效率,把整型、浮点型这些常用类型设置成值类型。
但有些CLR某些函数只接受引用类型参数,因此有了装箱与拆箱来把操作值类型常量包装成相应的引用类型,方便操作它们。

原文地址:https://www.cnblogs.com/wllhq/p/4641029.html