c#學習體會:使用 ref 和 out 傳遞數組(downmoon)

來源:互聯網
上載者:User

c#學習體會:使用 ref 和 out 傳遞數組(downmoon),希望與大家分享
1、與所有的 out 參數一樣,在使用數群組類型的 out 參數前必須先為其賦值,即必須由接受方為其賦值。例如:

public static void MyMethod(out int[] arr)
...{
   arr = new int[10];   // 數組arr的明確委派
}

2、與所有的 ref 參數一樣,數群組類型的 ref 參數必須由調用方明確賦值。因此不需要由接受方明確賦值。可以將數群組類型的 ref 參數更改為調用的結果。例如,可以為數組賦以 null 值,或將其初始化為另一個數組。例如:

public static void MyMethod(ref int[] arr)
...{
   arr = new int[10];   // arr初始化為一個新的數組
}

下面的兩個樣本說明 out 和 ref 在將數組傳遞給方法上的用法差異。

樣本 1
在此例中,在調用方(Main 方法)中聲明數組 myArray,並在 FillArray 方法中初始化此數組。然後將數組元素返回調用方並顯示。

using System;
class TestOut
...{
   static public void FillArray(out int[] myArray)
   ...{
      // 初始化數組(必須):
      myArray = new int[5] ...{1, 2, 3, 4, 5};
   }

   static public void Main()
   ...{
      int[] myArray; // 初始化數組(不是必須的!)

      // 傳遞數組給(使用out方式的)調用方:
      FillArray(out myArray);

      // 顯示數組元素
      Console.WriteLine("數組元素是:");
      for (int i=0; i < myArray.Length; i++)
         Console.WriteLine(myArray[i]);
   }
}

輸出
數組元素是:
1
2
3
4
5
樣本 2
在此例中,在調用方(Main 方法)中初始化數組 myArray,並通過使用 ref 參數將其傳遞給 FillArray 方法。在 FillArray 方法中更新某些數組元素。然後將數組元素返回調用方並顯示。

using System;
class TestRef
...{
   public static void FillArray(ref int[] arr)
   ...{
      // 根據需要建立一新的數組(不是必須的)
      if (arr == null)
         arr = new int[10];
      // 否則填充數組,就可以了
      arr[0] = 123;
      arr[4] = 1024;
   }

   static public void Main ()
   ...{
      //初始化數組:
      int[] myArray = ...{1,2,3,4,5}; 

      // 使用ref傳遞數組:
      FillArray(ref myArray);

      //顯示更新後的數組元素:
      Console.WriteLine("數組元素是:");
      for (int i = 0; i < myArray.Length; i++)
         Console.WriteLine(myArray[i]);
   }
}

輸出
數組元素是:
123
2
3
4
1024

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.