痞子龍㊣

C#零起点

 

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

#中out与ref的用法与区别

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

 }

}

}

posted on 2006-12-19 10:47  hnsjack(痞子龍)  阅读(420)  评论(0编辑  收藏  举报

导航