C# 中 ref 和out 的区别
out?參數前必須先為其賦值,即必須由被調用方為其賦值。
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 */?
ref?參數必須由調用方明確賦值。因此不需要由接受方明確賦值。
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*/?
區別:
ref和out的區別在C# 中,既可以通過值也可以通過引用傳遞參數。通過引用傳遞參數允許函數成員更改參數的值,并保持該更改。若要通過引用傳遞參數, 可使用ref或out關鍵字。ref和out這兩個關鍵字都能夠提供相似的功效,其作用也很像C中的指針變量。它們的區別是:
1、使用ref型參數時,傳入的參數必須先被初始化。對out而言,必須在方法中對其完成初始化。
2、使用ref和out時,在方法的參數和執行方法時,都要加Ref或Out關鍵字。以滿足匹配。
3、out適合用在需要retrun多個返回值的地方,而ref則用在需要被調用的方法修改調用者的引用的時候。
out
方法參數上的 out 方法參數關鍵字使方法引用傳遞到方法的同一個變量。當控制傳遞回調用方法時,在方法中對參數所做的任何更改都將反映在該變量中。
當希望方法返回多個值時,聲明 out 方法非常有用。使用 out 參數的方法仍然可以返回一個值。一個方法可以有一個以上的 out 參數。
若要使用 out 參數,必須將參數作為 out 參數顯式傳遞到方法。out 參數的值不會傳遞到 out 參數。
不必初始化作為 out 參數傳遞的變量。然而,必須在方法返回之前為 out 參數賦值。
屬性不是變量,不能作為 out 參數傳遞。
?
ref是??? 有進有出,而out是?????? 只出不進。
轉載于:https://www.cnblogs.com/mchuang/p/5006411.html
總結
以上是生活随笔為你收集整理的C# 中 ref 和out 的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL修改数据表存储引擎的3种方法介
- 下一篇: C#获取ip的示例