• 关于引用传递的测试题


    第一段程序:

       public static void change(int[] arr)
            {
                // both of the following changes will affect the original variables:
                arr[0] = 888;
                arr = new int[5] { -3, -1, -2, -3, -4 };
                Console.WriteLine((arr[0]).ToString());
            }
            public static void Main()
            {
                int[] myarray = new int[3];
                myarray[0] = 1;
                myarray[1] = 4;
                myarray[2] = 5;
                Console.WriteLine(myarray[0]);
                change(myarray);
                Console.WriteLine(myarray[0]);
                Console.ReadLine();
            }

    第二段程序:
            public static void change(ref int[] arr)
            {
                // both of the following changes will affect the original variables:
                arr[0] = 888;
                arr = new int[5] { -3, -1, -2, -3, -4 };
                Console.WriteLine((arr[0]).ToString());
            }
            public static void Main()
            {
                int[] myarray = new int[3];
                myarray[0] = 1;
                myarray[1] = 4;
                myarray[2] = 5;
                Console.WriteLine(myarray[0]);
                change(ref myarray);
                Console.WriteLine(myarray[0]);
                Console.ReadLine();
            }

    回答格式:

    第一段程序:XXX

    第二段程序:XXX

    答案:

      第一段程序:

      1

      -3

      888

      第二段程序:

      1

      -3

      -3

    解释:

    引用类型作为参数时:

    1、在修改变量本身时,结果类似于值传递,即不会改变传递前的变量的值

    2、在修改变量的属性或字段时,才是引用传递,会影响到传递前的变量的值

    3、参数使用了ref后,才是真正的引用传递,不管修改变量本身还是修改变量的属性或字段,都会影响到传递前的变量的值

  • 相关阅读:
    Bootstrap 3的box-sizing样式导致UEditor控件的图片无法正常缩放
    Npm install failed with “cannot run in wd”
    JQuery使用deferreds串行多个ajax请求
    使用HTML5的History API
    Christmas Trees, Promises和Event Emitters
    Node.js开发者最常范的10个错误
    Mongoose Schemas定义中timestamps选项的妙用
    Ubuntu上安装Robomongo及添加到启动器
    [nodemon] Internal watch failed: watch ENOSPC错误解决办法
    介绍两个Ubuntu上的桌面小工具
  • 原文地址:https://www.cnblogs.com/yuqilin/p/2163256.html
Copyright © 2020-2023  润新知