asp.net數組 ref和out傳遞數組

來源:互聯網
上載者:User

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的不同。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.