zoukankan      html  css  js  c++  java
  • 值类型与引用类型的区别

    一、概念讲解:

    1、值类型:

    包括:sbyte、short、int、long、float、double、decimal(以上值类型有符号)

       byte、ushort、uint、ulong(以上值类型无符号)

       bool、char

    2、引用类型:

    包括:对象类型、动态类型、字符串类型

    二、具体区别:

    1、值类型:

    byte b1 = 1;
    byte b2 = b1;
    Console.WriteLine("{0},{1}。", b1, b2);
    b2 = 2;
    Console.WriteLine("{0},{1}。", b1, b2);
    Console.ReadKey();

    解释:

    byte b1 = 1;声明b1时,在栈内开辟一个内存空间保存b1的值1。

    byte b2 = b1;声明b2时,在栈内开辟一个内存空间保存b1赋给b2的值1。

    Console.WriteLine("{0},{1}。", b1, b2);输出结果为1,1。

    b2 = 2;将b2在栈中保存的值1改为2。

    Console.WriteLine("{0},{1}。", b1, b2);输出结果为1,2。

    2、引用类型:

    string[] str1 = new string[] { "a", "b", "c" };
    string[] str2 = str1;
    for (int i = 0; i < str1.Length; i++)
    {
        Console.Write(str1[i] + " ");
    }
    Console.WriteLine();
    for (int i = 0; i < str2.Length; i++)
    {
        Console.Write(str2[i] + " ");
    }
    Console.WriteLine();
    str2[2] = "d";
    for (int i = 0; i < str1.Length; i++)
    {
        Console.Write(str1[i] + " ");
    }
    Console.WriteLine();
    for (int i = 0; i < str2.Length; i++)
    {
        Console.Write(str2[i] + " ");
    }
    Console.ReadKey();

    解释:

    string[] str1 = new string[] { "a", "b", "c" };声明str1时,首先在堆中开辟一个内存空间保存str1的值(假设:0a001),然后在栈中开辟一个内存空间保存0a001地址

    string[] str2 = str1;声明str2时,在栈中开辟一个内存空间保存str1赋给str2的地址

    for (int i = 0; i < str1.Length; i++)

    {

      Console.Write(str1[i] + " ");

    }

    Console.WriteLine();

    for (int i = 0; i < str2.Length; i++)

    {

      Console.Write(str2[i] + " ");

    }

    Console.WriteLine();

    输出结果为:

    a b c

    a b c

    str2[2] = "d";修改值是修改0a001的值

    for (int i = 0; i < str1.Length; i++)

    {

      Console.Write(str1[i] + " ");

    }

    Console.WriteLine();

    for (int i = 0; i < str2.Length; i++)

    {

      Console.Write(str2[i] + " ");

    }

    输出结果为:

    a b d

    a b d

    3、string类型:(特殊)

    string str1 = "abc";
    string str2 = str1;
    Console.WriteLine("{0},{1}。", str1, str2);
    str2 = "abd";
    Console.WriteLine("{0},{1}。", str1, str2);
    Console.ReadKey();

    解释:

    string str1 = "abc";声明str1时,首先在堆中开辟一个内存空间保存str1的值(假设:0a001),然后在栈中开辟一个内存空间保存0a001地址

    string str2 = str1;声明str2时,首先在堆中开辟一个内存空间保存str1赋给str2的值(假设:0a002),然后在栈中开辟一个内存空间保存0a002的地址

    Console.WriteLine("{0},{1}。", str1, str2);输出结果为:
    abc
    abc

    str2 = "abd";修改str2时,在堆中开辟一个内存空间保存修改后的值(假设:0a003),然后在栈中修改str2地址为0a003地址

    Console.WriteLine("{0},{1}。", str1, str2);输出结果为:
    abc
    abd

    堆中内存空间0a002将被垃圾回收利用。

    以上是我对值类型与引用类型的理解,希望可以给需要的朋友带来帮助。

  • 相关阅读:
    nginx 安装部署
    cordova 安装使用
    git 设置和取消代理
    SQL语句 合并列值 将一列的多个值合并成一行
    idea 注册码 地址:
    mac 安装redis
    redisTemplate 方法
    js 点击 隐藏弹出层
    windows 安装redis
    docker 安装redis
  • 原文地址:https://www.cnblogs.com/DingALing/p/12081081.html
Copyright © 2011-2022 走看看