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<thearray.length;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的不同。