首页 > Windows开发 > 详细

C# ref和out的区别

时间:2020-07-01 19:46:36      阅读:61      评论:0      收藏:0      [点我收藏+]

一、ref(引用型参数)和out(输出型参数)的区别

1、使用ref型参数时,传入的参数必须先被初始化,out型参数,必须在方法中对其完成初始化。

2、使用ref和out时,在方法的参数和执行方法时,都要加Ref或Out关键字,以满足匹配。

3、out适合用在需要retrun多个返回值的地方,而ref则用在需要被调用的方法修改调用者的引用的时候。

4、ref传进去的参数在函数内部可以直接使用,而out不可。

5、系统对ref的限制是更少一些的。

6、若要使用 ref 参数,必须将参数作为 ref 参数显式传递到方法,ref 参数的值被传递到 ref 参数。

7、当希望方法返回多个值时,声明 out 方法非常有用;使用 out 参数的方法仍然可以返回一个值。

8、ref 将值类型强制按引用类型进行传递

二、代码举例

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5 
 6             T t = new T();
 7             t.num = 5;
 8             ChangeT(ref t);
 9             Console.WriteLine(t.num);
10             string str;
11             string result;
12             result = Handle(out str);
13             Console.WriteLine(str);
14             Console.WriteLine(result);
15         }
16 
17         static string Handle(out string s)
18         {
19             s = "hello";
20             return "ok";
21         }
22 
23         static void ChangeT(ref T t)
24         {
25             t.num++;
26         }
27     }

 

C# ref和out的区别

原文:https://www.cnblogs.com/mojiejushi/p/13220609.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!