共用方式為


傳遞陣列當做參數 (C# 程式設計手冊)

更新:2007 年 11 月

您可以將陣列當做參數傳遞至方法。由於陣列是參考型別,因此方法可變更元素的值。

將一維陣列當做參數傳遞

您可以將初始化的一維陣列傳遞至方法。例如:

PrintArray(theArray);

上面這行所呼叫的方法可定義為:

void PrintArray(int[] arr)
{
    // method code
}

您也可以用一個步驟來初始化並傳遞新陣列。例如:

PrintArray(new int[] { 1, 3, 5, 7, 9 });

範例

以下範例將初始化一個字串陣列並將其當做參數傳遞至 PrintArray 方法,並在方法中顯示陣列的元素:

class ArrayClass
{
    static void PrintArray(string[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            System.Console.Write(arr[i] + "{0}", i < arr.Length - 1 ? " " : "");
        }
        System.Console.WriteLine();
    }

    static void Main()
    {
        // Declare and initialize an array:
        string[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

        // Pass the array as a parameter:
        PrintArray(weekDays);
    }
}
// Output: Sun Mon Tue Wed Thu Fri Sat

在下列程式碼中,會初始化二維陣列,並將其傳遞至會顯示陣列元素的 PrintArray 方法。

class ArrayClass2D
{
    static void PrintArray(int[,] arr)
    {
        // Display the array elements:
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 2; j++)
            {
                System.Console.WriteLine("Element({0},{1})={2}", i, j, arr[i, j]);
            }
        }
    }
    static void Main()
    {
        // Pass the array as a parameter:
        PrintArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();

    }
}
    /* Output:
        Element(0,0)=1
        Element(0,1)=2
        Element(1,0)=3
        Element(1,1)=4
        Element(2,0)=5
        Element(2,1)=6
        Element(3,0)=7
        Element(3,1)=8
    */

將多維陣列當做參數傳遞

您可以將初始化的多維陣列傳遞至方法。例如,如果 theArray 是二維陣列:

PrintArray(theArray);

上面這行所呼叫的方法可定義為:

void PrintArray(int[,] arr)
{
    // method code
}

您也可以用一個步驟來初始化並傳遞新陣列。例如:

PrintArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });

// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();

請參閱

概念

C# 程式設計手冊

參考

陣列 (C# 程式設計手冊)

一維陣列 (C# 程式設計手冊)

多維陣列 (C# 程式設計手冊)

不規則陣列 (C# 程式設計手冊)