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("\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關鍵字。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM