zoukankan      html  css  js  c++  java
  • C#数组按值和按引用传递数组区别

    C#中,存储数组之类对象的变量并不是实际存储对象本身,而是存储对象的引用。按值传递数组时,程序将变量传递给方法时,被调用方法接受变量的一个副本,因此在被调用时试图修改数据变量的值时,并不会影响变量的原始值;而按引用传递数组时,被调用方法接受的是引用的一个副本,因此在被调用时修改数据变量时,会改变变量的原始值。下面一个例子说明如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Array
    {
        class Program
        {
            public static void FirstDouble(int[] a)
            {
                for (int i = 0; i < a.Length; i++)
                {
                    a[i] = a[i] * 2;
                }
    
                a = new int[] { 11, 12, 13 };
            }
    
            public static void SecondDouble(ref int[] a)
            {
                for (int i = 0; i < a.Length; i++)
                {
                    a[i] = a[i] * 2;
                }
                a = new int[] { 11, 12, 13 };
            }
    
            public static void OutputArray(int[] array)
            {
                for (int i = 0; i < array.Length; i++)
                {
                    Console.WriteLine("{0}", array[i]);
                }
                //Console.WriteLine("
    ");
            }
    
            static void Main(string[] args)
            {
                int[] array = { 1, 2, 3 };
                Console.WriteLine("不带ref关键字方法调用前数组内容:");
                OutputArray(array);
                FirstDouble(array);
                Console.WriteLine("不带ref关键字方法调用后数组内容:");
                OutputArray(array);
                int [] array1={1,2,3};
                Console.WriteLine("带ref关键字方法调用前数组内容:");
                OutputArray(array1);
                SecondDouble(ref array1);
                Console.WriteLine("带ref关键字方法调用后数组内容:");
                OutputArray(array1);
                Console.ReadLine();
            }
        }
    }

    运行结果如下图:

    image

    注意的是:调用带ref关键字的方法时,参数中也要加ref关键字。

  • 相关阅读:
    Centos 6.5 在 Dell 服务器安装的记录
    【转载】你真的了解补码吗
    【转载】我对补码的理解
    记录一下家里双路由实现wifi漫游功能
    中国大学MOOC | C语言程序设计入门 第8周编程练习 翁恺
    华为卡刷包线刷方法
    串口通信
    端口复用和端口重映射
    软件仿真和硬件仿真
    FPGA之四位LED灯
  • 原文地址:https://www.cnblogs.com/shawnzhou/p/3317678.html
Copyright © 2011-2022 走看看