ref是传递参数的地址,out是返回值,

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

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace outAndref
{

class TestApp
{
 static void outTest(out int l, out int s)
 {
     //离开这个函数前,必须对x和y赋值,否则会报错。
  //y = x;
  //上面这行会报错,因为使用了out后,x和y都清空了,需要重新赋值,即使调用函数前赋过值也不行
  l = 1;
  s = 2;
 }
 static void refTest(ref int l, ref int s)
 {
  l = 1;
  s = l;
 }
 public static void Main()
 {
  //out test
     int a, b;
     //int a = 1;
     //int b = 23;
  //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 c1=11,d1=22;
  //int c1, d1;
  refTest(ref c1, ref d1);
  Console.WriteLine("c1={0};d1={1}",c1,d1);
 }
}


}

posted on 2010-08-26 00:41  MountainInk  阅读(180)  评论(0编辑  收藏  举报