zoukankan      html  css  js  c++  java
  • 关于引用传递的测试题

    第一段程序:

       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后,才是真正的引用传递,不管修改变量本身还是修改变量的属性或字段,都会影响到传递前的变量的值

  • 相关阅读:
    LeetCode算法题-Convert Sorted Array to Binary Search Tree(Java实现)
    LeetCode算法题-Binary Tree Level Order Traversal II(Java实现)
    LeetCode算法题-Maximum Depth of Binary Tree
    LeetCode算法题-Symmetric Tree(Java实现)
    LeetCode算法题-Same Tree(Java实现)
    基于任务的异步编程模式,Task-based Asynchronous Pattern
    Nito.AsyncEx 这个库
    暴力 六点钟
    夜晚 十点 React-Native 源码 暴力畜 系列
    夜晚 暴力 十点钟 jQuery 的 extend 实现 原理
  • 原文地址:https://www.cnblogs.com/yuqilin/p/2163256.html
Copyright © 2011-2022 走看看