詳解C#使用ref和out
在C#中,既可以通過值也可以通過引用傳遞參數(shù)。通過引用傳遞參數(shù)允許函數(shù)成員(方法、屬性、索引器、運(yùn)算符和構(gòu)造函數(shù))更改參數(shù)的值,并保持該更改。若要通過引用傳遞參數(shù),請C#使用ref和out傳遞數(shù)組。為簡單起見,本主題的示例中只使用了ref關(guān)鍵字。有關(guān)ref和out傳遞數(shù)組之間的差異的信息,請參見、C#使用ref和out傳遞數(shù)組。
本主題包括下列章節(jié):
◆傳遞值類型參數(shù)
◆傳遞引用類型參數(shù)
值類型變量直接包含其數(shù)據(jù),這與引用類型變量不同,后者包含對其數(shù)據(jù)的引用。因此,向方法傳遞值類型變量意味著向方法傳遞變量的一個(gè)副本。方法內(nèi)發(fā)生的對參數(shù)的更改對該變量中存儲(chǔ)的原始數(shù)據(jù)無任何影響。如果希望所調(diào)用的方法更改參數(shù)值,必須使用ref或out關(guān)鍵字通過引用傳遞該參數(shù)。為了簡單起見,以下示例使用ref。
下面的示例演示通過值傳遞值類型參數(shù)。通過值將變量myInt傳遞給方法SquareIt。方法內(nèi)發(fā)生的任何更改對變量的原始值無任何影響。
- //PassingParams1.cs
- usingSystem;
- classPassingValByVal
- ...{
- staticvoidSquareIt(intx)
- //Theparameterxispassedbyvalue.
- //ChangestoxwillnotaffecttheoriginalvalueofmyInt.
- ...{
- x*=x;
- Console.WriteLine("Thevalueinsidethemethod:{0}",x);
- }
- publicstaticvoidMain()
- ...{
- intmyInt=5;
- Console.WriteLine("Thevaluebeforecallingthemethod:{0}",
- myInt);
- SquareIt(myInt);//PassingmyIntbyvalue.
- Console.WriteLine("Thevalueaftercallingthemethod:{0}",
- myInt);
- }
- }
當(dāng)調(diào)用SquareIt時(shí),myInt的內(nèi)容被復(fù)制到參數(shù)x中,在方法內(nèi)將該參數(shù)求平方。但在Main中,myInt的值在調(diào)用SquareIt方法之前和之后是相同的。實(shí)際上,方法內(nèi)發(fā)生的更改只影響局部變量x。
下面的示例除使用ref關(guān)鍵字傳遞參數(shù)以外,其余與上面代碼相同。參數(shù)的值在調(diào)用方法后發(fā)生更改。
- //PassingParams2.cs
- usingSystem;
- classPassingValByRef
- ...{
- staticvoidSquareIt(refintx)
- //Theparameterxispassedbyreference.
- //ChangestoxwillaffecttheoriginalvalueofmyInt.
- ...{
- x*=x;
- Console.WriteLine("Thevalueinsidethemethod:{0}",x);
- }
- publicstaticvoidMain()
- ...{
- intmyInt=5;
- Console.WriteLine("Thevaluebeforecallingthemethod:{0}",
- myInt);
- SquareIt(refmyInt);//PassingmyIntbyreference.
- Console.WriteLine("Thevalueaftercallingthemethod:{0}",
- myInt);
- }
- }
以上介紹C#使用ref和out傳遞數(shù)組
【編輯推薦】