欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-09-05 08:29:10
在 c# 中,数组实际上是对象,而不只是像 c 和 c++ 中那样的可寻址连续内存区域。 array 是所有数组类型的抽象基类型。 可以使用 array 具有的属性以及其他...

在 c# 中,数组实际上是对象,而不只是像 c 和 c++ 中那样的可寻址连续内存区域。 array 是所有数组类型的抽象基类型。 可以使用 array 具有的属性以及其他类成员。 这种用法的一个示例是使用 length 属性来获取数组的长度。 下面的代码将 numbers 数组的长度(为 5)赋给名为 lengthofnumbers 的变量:

int[] numbers = { 1, 2, 3, 4, 5 };
int lengthofnumbers = numbers.length;

array 类提供了许多其他有用的方法和属性,用于排序、搜索和复制数组。
示例
此示例使用 rank 属性来显示数组的维数。

class testarraysclass
{
  static void main()
  {
    // declare and initialize an array:
    int[,] thearray = new int[5, 10];
    system.console.writeline("the array has {0} dimensions.", thearray.rank);
  }
}

输出:

 the array has 2 dimensions.

使用 ref 和 out 传递数组
与所有 out 参数一样,在使用数组类型的 out 参数前必须先为其赋值;即必须由被调用方为其赋值。例如:

static void testmethod1(out int[] arr)
{
  arr = new int[10];  // definite assignment of arr
}

与所有 ref 参数一样,数组类型的 ref 参数必须由调用方明确赋值。因此,不需要由被调用方明确赋值。可以将数组类型的 ref 参数更改为调用的结果。例如,可以为数组赋以 null 值,或将其初始化为另一个数组。例如:

static void testmethod2(ref int[] arr)
{
  arr = new int[10];  // arr initialized to a different array
}

下面两个示例演示了 out 与 ref 在将数组传递给方法时的用法差异。
在此示例中,在调用方(main 方法)中声明数组 thearray,并在 fillarray 方法中初始化此数组。然后,数组元素将返回调用方并显示。

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

    // keep the console window open in debug mode.
    system.console.writeline("press any key to exit.");
    system.console.readkey();
  }
}

输出:

    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