天天看點

C#中使用 ref 和 out 傳遞數組

C#

class TestOut
{
    static void FillArray(out int[] arr)
    {
        // Initialize the array:
        arr = new int[5] { 1, 2, 3, 4, 5 };
    }

    static void Main()
    {
        int[] theArray; // Initialization is not required

        // Pass the array to the callee using out:
        FillArray(out theArray);

        // Display the array elements:
        System.Console.WriteLine("Array elements are:");
        for (int i = 0; i < theArray.Length; i++)
        {
            System.Console.Write(theArray[i] + " ");
        }
    }
}
      

<script type="text/Javascript"> var ExpCollDivStr = ExpCollDivStr; ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl14ebe243f,"; var ExpCollImgStr = ExpCollImgStr; ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl14img,"; </script>輸出 1

Array elements are:

1 2 3 4 5

示例 2

在此例中,在調用方(Main 方法)中初始化數組 theArray,并通過使用 ref 參數将其傳遞給 FillArray 方法。在 FillArray 方法中更新某些數組元素。然後将數組元素傳回調用方并顯示。

C#

class TestRef
{
    static void FillArray(ref int[] arr)
    {
        // Create the array on demand:
        if (arr == null)
        {
            arr = new int[10];
        }
        // Fill the array:
        arr[0] = 1111;
        arr[4] = 5555;
    }

    static void Main()
    {
        // Initialize the array:
        int[] theArray = { 1, 2, 3, 4, 5 };

        // Pass the array using ref:
        FillArray(ref theArray);

        // Display the updated array:
        System.Console.WriteLine("Array elements are:");
        for (int i = 0; i < theArray.Length; i++)
        {
            System.Console.Write(theArray[i] + " ");
        }
    }
}
      

<script type="text/Javascript"> var ExpCollDivStr = ExpCollDivStr; ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl15c031095,"; var ExpCollImgStr = ExpCollImgStr; ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl15img,"; </script> <script type="text/Javascript"> var ExpCollDivStr = ExpCollDivStr; ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl17f50bc6d,"; var ExpCollImgStr = ExpCollImgStr; ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl17img,"; </script>輸出 2

Array elements are:

1111 2 3 4 5555

繼續閱讀