C#使用out和ref传递数组参数
闲来无聊拿着公司之前的asp.net项目看,重新激发了我学C#的冲动,哇咔咔~~~毕竟它太优雅了~
人懒手不勤,脑子再好用都是白搭,现在就开始贴我自学的漫漫过程吧,给未来的自己感谢自己的理由!!
今天说说ref和out
ref所传的参数必须由调用方明确赋值,被调用方可以对其进行修改;
out所传的参数就不必由调用方明确赋值了.
将这层意思应用到数组类型的参数上,也就是说,ref传递的数组必须是调用函数里已经初始化好的,而被调函数可对其进行某些元素的在赋值或者初始化.
使用out传递数组就无所谓是不是已在主调函数中初始化好的了.
贴个例子(取自C#编程指南):
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(); } } /* Output: Array elements are: 1 2 3 4 5 */
***********************************************************************************************************************************************************
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(); } } /* Output: Array elements are: 1111 2 3 4 5555 */