C#使用ref和out傳遞數組


一、使用ref參數傳遞數組

數組類型的ref參數必須由調用方明確賦值。因此,接受方不需要明確賦值。接受方數組類型的ref參數能夠修改調用方數組類型的結果。可以將接受方的數組賦以null值,或將其初始化為另一個數組。請閱讀引用型參數。

示例:

在調用方法(Main方法)中初始化數組array,並使用ref參數將其傳遞給theArray方法。在theArray方法中更新某些數組元素,然后將數組元素返回調用方並顯示出來。
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    class Program
    {
        static void theArray(ref int[] arr) // 接受方不需要明確賦值
        {
            if (arr == null)       // 根據需要創建一個新的數組(不是必須的)
            {
                arr = new int[10]; // 將數組賦以null值,或將其初始化為另一個數組
            }
            arr[0] = 11;
            arr[4] = 55;
        }
        static void Main(string[] args)
        {
            // C#使用ref參數傳遞數組-www.baike369.com
            int[] array = { 1, 2, 3, 4, 5 };
            theArray(ref array);            // 使用ref傳遞數組,調用方明確賦值
            Console.Write("數組元素為:");
            for (int i = 0; i < array.Length; i++)
            {
                Console.Write(array[i] + " ");
            }
            Console.ReadLine();
        }
    }
}

運行結果:
 
數組元素為:11 2 3 4 55

二、使用out參數傳遞數組
被調用方在使用數組類型的out參數時必須為其賦值。請閱讀輸出參數。

示例:

在調用方方法(Main方法)中聲明數組array,並在theArray方法中初始化此數組。然后將數組元素返回到調用方並顯示出來。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    class Program
    {
        static void theArray(out int[] arr)
        {
            arr = new int[]{0,2,4,6,8}; // 必須賦值
        }
        static void Main(string[] args)
        {
            int[] array;
            theArray(out array);           // 傳遞數組給調用方
            Console.Write("數組元素為:"); // 顯示數組元素
            for (int i = 0; i < array.Length; i++)
            {
                Console.Write(array[i] + " ");
            }
            Console.ReadLine();
        }
    }
}

運行結果:

數組元素為:0 2 4 6 8


免責聲明!

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



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