注册 登录
编程论坛 ASP.NET技术论坛

在C#中out是什么意思

zuglog2133 发布于 2008-10-27 21:06, 7224 次点击
在c#中out是什么意思,out在什么情况下用?
谢谢
6 回复
#2
bygg2008-10-27 21:16
[bo]转------->[/bo]

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);
 }
}

MSDN: http://msdn.(VS.80).aspx

[[it] 本帖最后由 bygg 于 2008-10-28 12:54 编辑 [/it]]
#3
righgrea2008-10-28 09:58
楼上的讲解很详细!赞一个。
#4
zsf20062008-10-28 12:18
不愧为斑竹,顶个先!
#5
sunjinfei_god2008-10-29 11:08
回复 1# 的帖子
out可以在传入参数的时候可以初始化也可以不初始化,这样比较灵活,但灵活的另一面就是在调用形参为out的方法中必须要给变量赋值,这样但对增加了回调函数的负担,是有些区别的
#6
zuglog21332008-10-29 17:51
谢谢
#7
dubaokun2010-08-14 18:12
讲的很彻底很好
1