码迷,mamicode.com
首页 > 其他好文 > 详细

out ref区别

时间:2014-12-06 12:37:52      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:style   color   使用   sp   div   bs   ef   amp   as   

1、使用ref型参数时,传入的参数必须先被初始化。对out而言,必须在方法中对其完成初始化。

2、out适合用在需要retrun多个返回值的地方,而ref则用在需要被调用的方法修改调用者的引用的时候。
 
两者都是按地址传递的,使用后都将改变原来的数值。类似C++的指针(*和#)
ref可以把参数的数值传递进函数,out是要把参数清空,就是说你无法把一个数值从out传递进去的,out进去后,参数的数值为空,所以你必须初始化一次。这个就是两个的区别,或者说就像有的网友说的,ref是有进有出,out是只出不进。经典!!!

以下来自MSDN:

out:



class OutReturnExample


     static void Method(out int i, out string s1, out string s2) 

     {

      i = 44; s1 = "I‘ve been returned"; s2 = null; 

      } 

      static void Main() 

     { 

        int value; string str1, str2; 

    Method(out value, out str1, out str2); 

       // value is now 44 

   // str1 is now "I‘ve been returned" 

  // str2 is (still) null;

      } 

 }

ref:





ref中的original可以被传入 out中的value和str1 str2不能被传入

out适合用在需要多个输出结果或者值的地方,而ref则用在需要被调用的方法修改调用者的引用的时候。
还有就是属性不能作为out传入。

class RefRefExample

{
    static void Method(ref string s)
    {
        s = "changed";
    }
    static void Main()
    {
        string str = "original";
        Method(ref str);
        // str is now "changed"

      
    }
}

out ref区别

标签:style   color   使用   sp   div   bs   ef   amp   as   

原文地址:http://www.cnblogs.com/0515offer/p/4148082.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!