软件编程
位置:首页>> 软件编程>> C#编程>> C#中out与ref的区别实例解析

C#中out与ref的区别实例解析

作者:shichen2014  发布时间:2022-01-27 13:29:09 

标签:C#,out,ref,区别

本文实例讲述了C#中Out与Ref的区别,可以加深C#程序设计人员对Out和Ref用法的理解,具体分析如下:

一、区别分析:

Out和Ref作为参数传递到方法体中,所传递的都是引用地址,两者在操作上本身没有区别。

但Out传递到方法体时,参数会清空,这意味着在方法体内使用Out参数前必须赋值。

而Ref传递到方法体时,其参数也是一起被传递进来,所以作为Ref参数传递,方法体中可以不对其参数赋值。

二、实例代码如下:


class Program
{
 /*ref是有进有出,out是只出不进*/
 static void Main(string[] args)
 {
   /*作为Out参数传递 传递前可以不初始化*/
   string outString = "This is the outString value";
   Console.WriteLine(outString);
   outMethod(out outString);
   Console.WriteLine(outString);

/*作为Ref参数传递 传递前必须初始化*/
   string refString = "This is the refString value";
   Console.WriteLine(refString);
   refMethod(ref refString);
   Console.WriteLine(refString);
   Console.ReadLine();

}
 static bool outMethod(out string str)
 {
   /*作为Out参数传递 传递到方法体后 参数被清空*/
   //Console.WriteLine(str); Use of unassigned out parameter 'str'
   /*作为Out参数传递 值必须在方法体内赋值*/
   /*作为Out参数传递 返回前值必须初始化*/
   str = "This is the new outString value";
   return true;
 }
 static bool refMethod(ref string str)
 {
   Console.WriteLine(str);
   /*作为Ref参数传递 返回前值可以不初始化*/
   return true;
 }
}

希望本文所述实例对大家C#程序设计有一定的帮助。

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com