Ref和Out区别

ref和out都是C#中的关键字,所实现的功能也差不多,都是指定一个参数按照引用传递。对于编译后的程序而言,它们之间没有任何区别,也就是说它们只有语法区别。总结起来,他们有如下语法区别:

1. ref传进去的参数必须在调用前初始化,out不必,即:
  int i;
  SomeMethod( ref i );//语法错误
  SomeMethod( out i );//通过
2. ref传进去的参数在函数内部可以直接使用,out的函数会清空变量,不能直接使用,即
  public void SomeMethod(ref int i)
  {
     int j=i;//通过
     //...
  }
  public void SomeMethod(out int i)
  {
     int j=i;//语法错误
  }
3. ref传进去的参数在函数内部可以不被修改,但out必须在离开函数体前进行赋值。

总结:
应该说,系统对ref的限制是更少一些的。out虽然不要求在调用前一定要初始化,但是其值在函数内部是不可见的,也就是不能使用通过out传进来的值,并且一定要赋一个值。也就是说函数承担初始化这个变量的责任。 

具体代码:

using system;
class testapp
{
 
static void outtest(out int x, out int y)
 {
//离开这个函数前,必须对x和y赋值,否则会报错。 
  
//y = x;

        //int k = 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);
 }

 

 

posted @ 2009-12-11 11:33  ┆雨落┆  阅读(205)  评论(0)    收藏  举报