c#中out和ref使用小结

1、out必须在函数体内初始化,在外面初始化没意义。也就是说,out型的参数在函数体内不能得到外面传进来的初始值。
2、ref必段在函数体外初始化。
3、两都在函数体的任何修改都将影响到外面

ref是传递参数的地址,out是返回值,两者有一定的相同之处,不过也有不同点。

使用ref前必须对变量赋值,out不用。

  out的函数会清空变量,即使变量已经赋值也不行,退出函数时所有out引用的变量都要赋值,ref引用的可以修改,也可以不修改。

  区别可以参看下面的代码:

 1 None.gif using  system;
 2 None.gif class  testapp
 3 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 4InBlock.gif static void outtest(out int x, out int y)
 5ExpandedSubBlockStart.gifContractedSubBlock.gif dot.gif{/离开这个函数前,必须对x和y赋值,否则会报错。 
 6InBlock.gif  /= x; 
 7InBlock.gif  /上面这行会报错,因为使用了out后,x和y都清空了,需要重新赋值,即使调用函数前赋过值也不行 
 8InBlock.gif  x = 1;
 9InBlock.gif  y = 2;
10ExpandedSubBlockEnd.gif }

11InBlock.gif static void reftest(ref int x, ref int y)
12ExpandedSubBlockStart.gifContractedSubBlock.gif dot.gif
13InBlock.gif  x = 1;
14InBlock.gif  y = x;
15ExpandedSubBlockEnd.gif }

16InBlock.gif public static void main()
17ExpandedSubBlockStart.gifContractedSubBlock.gif dot.gif{
18InBlock.gif  /out test
19InBlock.gif  int a,b;
20InBlock.gif  /out使用前,变量可以不赋值
21InBlock.gif  outtest(out a, out b);
22InBlock.gif  console.writeline("a={0};b={1}",a,b);
23InBlock.gif  int c=11,d=22;
24InBlock.gif  outtest(out c, out d);
25InBlock.gif  console.writeline("c={0};d={1}",c,d);
26InBlock.gif
27InBlock.gif  /ref test
28InBlock.gif  int m,n;
29InBlock.gif  /reftest(ref m, ref n); 
30InBlock.gif  /上面这行会出错,ref使用前,变量必须赋值
31InBlock.gif
32InBlock.gif  int o=11,p=22;
33InBlock.gif  reftest(ref o, ref p);
34InBlock.gif  console.writeline("o={0};p={1}",o,p);
35ExpandedSubBlockEnd.gif }

36ExpandedBlockEnd.gif}
 
37 None.gif

转载于:https://www.cnblogs.com/yunfeng8967/articles/1114748.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值