C# 引用类型 Customer customer1; customer1 = new Customer();和Customer custumer1 = new Customer();的区别

  引用类型的分配相当复杂,该博文只说明这两种实例化的区别。

static void Main(string[] args) {
    Customer customer1;
    customer1 = new Customer();
}

  Customer customer1;

  声明一个 Customer引用customer1,会在栈上给这个引用分配存储空间。但这只是一个引用,而不是实际的Customer对象,customer1引用占用4个字节的空间(GetHashCode()返回的是一个int类型)。

  customer1 = new Customer();

  这行代码完成了以下操作:首先,它分配内存,以存储Customer对象(一个真正的对象,不只是一个地址)。然后把变量customer1的值设置为分配给新的Customer对象的内部地址(它会调用当前调用的构造函数初始化类中的字段)。Customer实例没有存放在栈中,而是存放在堆中。假定当前new Customer()对象占用32个字节,.NET 运行库会在堆中选取一个未使用的且包含32字节的连续块。

static void Main(string[] args) {
    Customer customer1 = new Customer();
}

该操作会把上面两步合并成一步来执行。

还有一个问题就是:

static void Main(string[] args) {
    Customer customer1;
    Customer customer1 = null;
}

这两种方式有什么区别。

原文地址:https://www.cnblogs.com/grj1046/p/2851500.html