使用C#一年多了,竟然是昨天才知道C# 中有 ref  和 out的用法
于是看了一会儿demo,大致搞懂是啥东西了。

这种方法的优点就是可以返回多个值,不再受函数返回一个值的限制,很爽。

其实也很简单,就好像C++里的&(引用)
传递的是实际参数的地址,修改参数值,就会导致直接将内存中该地址中的值修改掉
所以之后输出该参数的值将是修改之后的值

需要注意的是:属性不是变量,不能作为 out 参数传递。

还有如下重载也是不允许的
1C#中的 ref 和 outclass MyClass 
2

对于ref 和 out给个简单的demo
相信一看就明白了

 1C#中的 ref 和 out// PassingParams2.cs 
 2C#中的 ref 和 outusing System;
 3C#中的 ref 和 outclass PassingValByRef
 4 

输出
The value before calling the method: 5
The value inside the method: 25
The value after calling the method: 25

代码讨论
本示例中,传递的不是 myInt 的值,而是对 myInt 的引用。参数 x 不是 int 类型,它是对 int 的引用(本例中为对 myInt 的引用)。因此,当在方法内对 x 求平方时,实际被求平方的是 x 所引用的项:myInt。


但是ref 和 out 也存在一些区别:

与所有的 out 参数一样,在使用数组类型的 out 参数前必须先为其赋值,即必须由接受方为其赋值。例如:

public static void MyMethod(out int[] arr) 
{
   arr = new int[10];   // definite assignment of arr
}

与所有的 ref 参数一样,数组类型的 ref 参数必须由调用方明确赋值。因此不需要由接受方明确赋值。可以将数组类型的 ref 参数更改为调用的结果。例如,可以为数组赋以 null 值,或将其初始化为另一个数组。例如:

public static void MyMethod(ref int[] arr) 
{
   arr = new int[10];   // arr initialized to a different array
}

下面给出两个demo

示例 1

在此例中,在调用方(Main 方法)中声明数组 myArray,并在 FillArray 方法中初始化此数组。然后将数组元素返回调用方并显示。

 

 1C#中的 ref 和 outusing System; 
 2C#中的 ref 和 outclass TestOut 
 3

输出
Array elements are:
1
2
3
4
5


示例 
2
在此例中,在调用方(Main 方法)中初始化数组 myArray,并通过使用 ref 参数将其传递给 FillArray 方法。在 FillArray 方法中更新某些数组元素。然后将数组元素返回调用方并显示。

 1C#中的 ref 和 outusing System; 
 2C#中的 ref 和 outclass TestRef 
 3

输出

Array elements are:
123
2
3
4
1024

 


 



相关文章:

  • 2022-03-04
  • 2021-07-29
  • 2021-09-18
  • 2021-09-13
  • 2022-01-05
  • 2021-11-08
猜你喜欢
  • 2021-08-14
  • 2022-01-14
  • 2021-12-29
  • 2021-10-20
  • 2022-01-05
相关资源
相似解决方案