C#参数不同点简单介绍

C#参数还是比较常见的东西,这里我们主要介绍C#参数不同点,包括介绍使用ref前必须对变量赋值,out不用等方面。

ref是传递参数的地址,out是返回值,两者有一定的相同之处,不过也有C#参数不同点。使用ref前必须对变量赋值,out不用。out的函数会清空变量,即使变量已经赋值也不行,退出函数时所有out引用的变量都要赋值,ref引用的可以修改,也可以不修改。

C#参数不同点可以参看下面的代码:

 
 
 
  1. using System;  
  2. class TestApp  
  3. {  
  4. static void outTest(out int x, out int y)  
  5. {//离开这个函数前,必须对x和y赋值,否则会报错。  
  6. //y = x;  
  7. //上面这行会报错,因为使用了out后,x和y都清空了,
    需要重新赋值,即使调用函数前赋过值也不行  
  8. x = 1;  
  9. y = 2;  
  10. }  
  11. static void refTest(ref int x, ref int y)  
  12. {  
  13. x = 1;  
  14. y = x;  
  15. }  
  16. public static void Main()  
  17. {  
  18. //out test  
  19. int a,b;  
  20. //out使用前,变量可以不赋值  
  21. outTest(out a, out b);  
  22. Console.WriteLine("a={0};b={1}",a,b);  
  23. int c=11,d=22;  
  24. outTest(out c, out d);  
  25. Console.WriteLine("c={0};d={1}",c,d);  
  26.  
  27. //ref test  
  28. int m,n;  
  29. //refTest(ref m, ref n);  
  30. //上面这行会出错,ref使用前,变量必须赋值  
  31.  
  32. int o=11,p=22;  
  33. refTest(ref o, ref p);  
  34. Console.WriteLine("o={0};p={1}",o,p);  
  35. }  

以上介绍C#参数不同点

【编辑推荐】

  1. C#与VB7比较详解
  2. C#连接Access浅析
  3. C#创建XML Web services学习经验
  4. C# Windows应用程序概述
  5. C# SmartPhone程序学习笔记
THE END