zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#数组按值和按引用传递数组区别

c#数组 区别 引用 传递
2023-09-11 14:16:45 时间

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("\n");
        }

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

 

 

 public static void Test()
        {
            double[] array = new double[4] { 0, 1, 2, 3 };
            A a1 = new A();
            A a2 = new A();
            a1.value = array;
            a2.value = array;
            a1.value[0] = 9999;//a1和a2都改变了,这里array是引用类型


        }