C#编程中使用ref和out关键字来传递数组对象的用法

2019-12-26 16:55:37于海丽

输出:


    Array elements are:
    1 2 3 4 5  

    
在此示例中,在调用方(Main 方法)中初始化数组 theArray,并通过使用 ref 参数将其传递给 FillArray 方法。在 FillArray 方法中更新某些数组元素。然后,数组元素将返回调用方并显示。


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] + " ");
    }

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

输出:


    Array elements are:
    1111 2 3 4 5555


注:相关教程知识阅读请移步到c#教程频道。