ref vs out. C#

來源:互聯網
上載者:User

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

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.