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