【www.gdgbn.com--安卓教程】

asp教程.net数组 ref和out传递数组

与所有的out参数一样,在使用数组类型的out参数前必须先为其赋值,即必须由被调用方为其赋值

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);
  }
 }
 //output:the array has 2 dimensions


数组实际上是对象【.net的所有对象都是派生自object对象】,而不只是像c和c++中那样的可寻址连续内存区域。array是所有数组是所有数组类型的抽象基类型。可以使用array具有属性以及其他成员。例如使用length属性来获取数组的长度:

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


使用ref和out传递数组
。例如:

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

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

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

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

class testout
{
    static void fillarray(out int[] arr)
    {
        arr = new int[5] {1,2,3,4,5};      
        }
    static void main()
    {
        int[] thearray;
        fillarray(out thearray);
        system.console.writeline("array elements are:");
        for(int i=0;i         {
            system.console.write(thearray[i] +" ");
            }
            system.console.writeline("press any key to exit.");
        }
    }

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

class testref
{
    static void fillarray(ref int[] arr)
    {
        int (arr == null)
        arr = new int[10];
        }
        arr[0] = 1111;
        arr[4] = 5555;
    }
  
    static void main()
    {
        int[] thearray = {1,2,3,4,5};
        fillarray(ref thearray);
        system.console.writeline("array elements are:");
        for (int i = 0; i < thearray.length; i++)
        {
            system.console.write(thearray[i] + " ");
        }

        }

       
ps教程:注意理解out与ref的不同。

本文来源:http://www.gdgbn.com/shoujikaifa/29444/