现在的位置: 首页 > 综合 > 正文

c#中out与ref的用法与区别

2013年09月02日 ⁄ 综合 ⁄ 共 580字 ⁄ 字号 评论关闭

 

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

例:

using System;

namespace ConsoleApplication1
{
 class C
 {
  public static void reffun(ref string str)
  {
   str += " fun";
  }

  public static void outfun(out string str)
  {
   str = "test";     //必须在函数体内初始
   str += " fun";
  }
 }

 class Class1
 {
  [STAThread]
  static void Main(string[] args)
  {
   string test1 = "test";
   string test2;                  //没有初始
   C.reffun( ref test1 );     //正确
   C.reffun( ref test2 );     //错误,没有赋值使用了test2
   C.outfun( out test1 );    //正确,但值test传进去
   C.outfun( out test2 );    //正确

   Console.Read();
  }
 }
}

 

抱歉!评论已关闭.