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关键字。

  • 相关阅读:
    如何快速部署Oracle Database
    有关Oracle统计信息的知识点
    索引的重建
    利用Openfiler配置基于文件系统的网络存储
    Linux命令(007) -- systemctl
    使用mysqldump导出数据库(表)
    文件处理.Windows.Fastcopy.3.50.x64.文件复制简体中文破解版(验证版)
    oracle 修改数据 保险方法
    oracle存储过程、声明变量、for循环--后期添加游标 if 、decode、 case when
    Oracle 游标使用全解
  • 原文地址:https://www.cnblogs.com/shawnzhou/p/3317678.html
Copyright © 2011-2022 走看看