C#中out和ref的区别

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

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

  out的函数会清空变量,即使变量已经赋值也不行,退出函数时所有out引用的变量都要赋值,ref引用的可以修改,也可以不修改。
 
  区别可以参看下面的代码:

using System;
class TestApp
{
 static void outTest(out int x, out int y)
 {//离开这个函数前,必须对x和y赋值,否则会报错。
  //y = x;
  //上面这行会报错,因为使用了out后,x和y都清空了,需要重新赋值,即使调用函数前赋过值也不行
  x = 1;
  y = 2;
 }
 static void refTest(ref int x, ref int y)
 {
  x = 1;
  y = x;
 }
 public static void Main()
 {
  //out test
  int a,b;
  //out使用前,变量可以不赋值
  outTest(out a, out b);
  Console.WriteLine("a={0};b={1}",a,b);
  int c=11,d=22;
  outTest(out c, out d);
  Console.WriteLine("c={0};d={1}",c,d);

  //ref test
  int m,n;
  //refTest(ref m, ref n);
  //上面这行会出错,ref使用前,变量必须赋值

  int o=11,p=22;
  refTest(ref o, ref p);

    Console.WriteLine("o={0};p={1}", o, p);

运行结果:

a=1;b=2
c=1;d=2
o=1;p=1

 总结:out是必须在函数(方法)里赋值,在外面赋值是不起作用的,ref必须在外面赋值,不过在里面可以修改值

摘自-:http://www.cnblogs.com/zhangronghua/archive/2006/11/13/558883.html

 

 

 //为了在ref 中做特殊处理而用
        static void refTest(ref int x, ref int y)
        {
            if (x > 20)
            {
                x = 100;
                y = x;
            }
            else {
                x = 15;
                y = x;
            }
        }

int o = 11, p = 22;
refTest(ref o, ref p);//

运行结果是 o=15,p=15

ref是为了通过外面传入值,然后在方法里面做一些判断,然后返回结果的值。

out 是为了在方法里面获得值,然后输出来。

posted @ 2012-12-20 23:02  山水中华  阅读(203)  评论(0编辑  收藏  举报