欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

C# 中 ref 和out 的区别

发布时间:2024/7/19 51 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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 的区别的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。