详解C#使用ref和out

在C#中,既可以通过值也可以通过引用传递参数。通过引用传递参数允许函数成员(方法、属性、索引器、运算符和构造函数)更改参数的值,并保持该更改。若要通过引用传递参数,请C#使用ref和out传递数组。为简单起见,本主题的示例中只使用了ref关键字。有关ref和out传递数组之间的差异的信息,请参见、C#使用ref和out传递数组。

本主题包括下列章节:
◆传递值类型参数
◆传递引用类型参数

值类型变量直接包含其数据,这与引用类型变量不同,后者包含对其数据的引用。因此,向方法传递值类型变量意味着向方法传递变量的一个副本。方法内发生的对参数的更改对该变量中存储的原始数据无任何影响。如果希望所调用的方法更改参数值,必须使用ref或out关键字通过引用传递该参数。为了简单起见,以下示例使用ref。

下面的示例演示通过值传递值类型参数。通过值将变量myInt传递给方法SquareIt。方法内发生的任何更改对变量的原始值无任何影响。

 
 
 
  1. //PassingParams1.cs  
  2. usingSystem;  
  3. classPassingValByVal  
  4. ...{  
  5. staticvoidSquareIt(intx)  
  6. //Theparameterxispassedbyvalue.  
  7. //ChangestoxwillnotaffecttheoriginalvalueofmyInt.  
  8. ...{  
  9. x*=x;  
  10. Console.WriteLine("Thevalueinsidethemethod:{0}",x);  
  11. }  
  12. publicstaticvoidMain()  
  13. ...{  
  14. intmyInt=5;  
  15. Console.WriteLine("Thevaluebeforecallingthemethod:{0}",  
  16. myInt);  
  17. SquareIt(myInt);//PassingmyIntbyvalue.  
  18. Console.WriteLine("Thevalueaftercallingthemethod:{0}",  
  19. myInt);  
  20. }  

当调用SquareIt时,myInt的内容被复制到参数x中,在方法内将该参数求平方。但在Main中,myInt的值在调用SquareIt方法之前和之后是相同的。实际上,方法内发生的更改只影响局部变量x。

下面的示例除使用ref关键字传递参数以外,其余与上面代码相同。参数的值在调用方法后发生更改。

 
 
 
  1. //PassingParams2.cs  
  2. usingSystem;  
  3. classPassingValByRef  
  4. ...{  
  5. staticvoidSquareIt(refintx)  
  6. //Theparameterxispassedbyreference.  
  7. //ChangestoxwillaffecttheoriginalvalueofmyInt.  
  8. ...{  
  9. x*=x;  
  10. Console.WriteLine("Thevalueinsidethemethod:{0}",x);  
  11. }  
  12. publicstaticvoidMain()  
  13. ...{  
  14. intmyInt=5;  
  15. Console.WriteLine("Thevaluebeforecallingthemethod:{0}",  
  16. myInt);  
  17. SquareIt(refmyInt);//PassingmyIntbyreference.  
  18. Console.WriteLine("Thevalueaftercallingthemethod:{0}",  
  19. myInt);  
  20. }  

以上介绍C#使用ref和out传递数组

【编辑推荐】

  1. 如何用C#和ADO.NET访问
  2. 浅析C# Switch语句
  3. C#验证输入方法详解
  4. 简单介绍C# 匿名方法
  5. C# FileSystemWatcher对象
THE END