日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

C# 中 ref 和out 的区别

發布時間:2024/7/19 C# 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 的区别的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。