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

  • 相关阅读:
    Echarts框架的使用
    变身windows达人,用运行命令直接启动所有应用程序
    Google为何这么屌
    骗子利用淘宝支付宝退款欺诈
    卡常技巧
    C++set用法
    分块大法好
    高精度乘法
    phpstudy初谈(基础教程)
    读入,输出优化
  • 原文地址:https://www.cnblogs.com/shawnzhou/p/3317678.html
Copyright © 2011-2022 走看看