近段时间,有几个刚刚开始学习C#语言的爱好者问我:C#中的函数,其参数的传递,按值传递和按引用传递有什么区别。针对这一问题,我简单写了个示例程序,用以讲解,希望我没有把他们绕晕。因为,常听别人说起:“你不说我还明白,你一说,我就糊涂了”。 
    好,现在开始吧。 
    我们知道,在C#中,类型有值类型(例如int)和引用类型(例如string)之分,传递参数有按值传递和按引用传递之分。这样,简单的组合一下,我们可以得到以下几种传递方式:(1)按值传递值类型。(2)按值传递引用类型。(3)按引用传递值类型。(4)按引用传递引用类型。一般来说,除非使用特定的关键字(ref和out)否则参数是按值传递的。也就是说,会传递一个副本。传递副本的一个好处是,可以避免误操作而影响了原始值。原因是在被调用的函数体内,操作的是副本的值,而不是原始值。当然,传递副本也是有副作用的,最为突出的应该是由于复制而产生的性能损耗,这点在大型的值类型身上尤为突出。那么C#的编译器的默认行为为什么不是使用按引用传递参数呢?呵呵,其实我没仔细深入思考过这个问题。我猜测,是因为安全因素吧,就是怕函数误操作了原始值。这点应该和C#的编译器要求显示使用关键字(ref和out)差不多,都是为了清楚地表达使用的意图,以避免误操作。使用ref等关键字,暗示函数调用者知道,在函数体内,也许存在修改原始值的语句,会改变参数的值(或者叫状态)。 
    用个简单的示例演示一下。 
    示例代码如下所示:

  1. using System;
  2. namespace DonLiang
  3. {
  4. class Sample
  5. {
  6. 值类型测试函数#region 值类型测试函数
  7. public static void foo(int x)
  8. {
  9. x = 10;
  10. }
  11. //*
  12. public static void foo(ref int x)
  13. {
  14. x = 10;
  15. }
  16. //*/
  17. /**//*
  18. public static void foo(out int x)
  19. {
  20. x = 10;
  21. }
  22. //*/
  23. #endregion
  24. 辅助引用类型#region 辅助引用类型
  25. public class Point
  26. {
  27. private int m_x;
  28. private int m_y;
  29. public Point()
  30. {
  31. m_x = 0;
  32. m_y = 0;
  33. }
  34. public Point(int x, int y)
  35. {
  36. m_x = x;
  37. m_y = y;
  38. }
  39. public void Change(int x, int y)
  40. {
  41. m_x = x;
  42. m_y = y;
  43. }
  44. public override string ToString()
  45. {
  46. return string.Format("The Point is ({0},{1})", m_x.ToString(), m_y.ToString());
  47. }
  48. }
  49. #endregion
  50. 引用类型测试函数#region 引用类型测试函数
  51. public static void foo(Point p)
  52. {
  53. p.Change(10, 10);
  54. }
  55. public static void foo(ref Point p)
  56. {
  57. p.Change(100, 100);
  58. }
  59. public static void other(Point p)
  60. {
  61. Point tmp = new Point(13, 16);
  62. p = tmp;
  63. }
  64. public static void other(ref Point p)
  65. {
  66. Point tmp = new Point(138, 168);
  67. p = tmp;
  68. }
  69. #endregion
  70. Main#region Main
  71. static void Main(string[] args)
  72. {
  73. int n = 5;
  74. //call the foo(int x) method and check what happened.
  75. Console.WriteLine("before call foo(int x) the n = " + n.ToString());
  76. foo(n);
  77. Console.WriteLine("after call foo(int x) the n = " + n.ToString());
  78. Console.WriteLine("--------------------------------------------------------------");
  79. //call the foo(ref int x) method and check what happened.
  80. Console.WriteLine("before call foo(ref int x) the n = " + n.ToString());
  81. foo(ref n);
  82. //foo(out n);
  83. Console.WriteLine("after call foo(ref int x) the n = " + n.ToString());
  84. Console.WriteLine("--------------------------------------------------------------");
  85. Point p = new Point(5, 5);
  86. Point q = p;
  87. //call the foo(Point p) method and check what happened.
  88. Console.WriteLine("before call foo(Point p) the p = " + p.ToString());
  89. foo(p);
  90. Console.WriteLine("after call foo(Point p) the p = " + p.ToString());
  91. Console.WriteLine("q = " + q.ToString());
  92. Console.WriteLine("--------------------------------------------------------------");
  93. //call the foo(ref Point p) method and check what happened.
  94. Console.WriteLine("before call foo(ref Point p) the n = " + p.ToString());
  95. foo(ref p);
  96. Console.WriteLine("after call foo(ref Point p) the n = " + p.ToString());
  97. Console.WriteLine("q = " + q.ToString());
  98. Console.WriteLine("--------------------------------------------------------------");
  99. //call the other(Point p) method and check what happened.
  100. Console.WriteLine("before call other(Point p) the n = " + p.ToString());
  101. other(p);
  102. Console.WriteLine("after call other(Point p) the n = " + p.ToString());
  103. Console.WriteLine("q = " + q.ToString());
  104. Console.WriteLine("--------------------------------------------------------------");
  105. //call the other(ref Point p) method and check what happened.
  106. Console.WriteLine("before call other(ref Point p) the n = " + p.ToString());
  107. other(ref p);
  108. Console.WriteLine("after call other(ref Point p) the n = " + p.ToString());
  109. Console.WriteLine("q = " + q.ToString());
  110. Console.ReadLine();
  111. }
  112. #endregion
  113. }
  114. }

接下来,简单分析一下这个结果: 
    (1)按值传递值类型 
    初始值为5,调用函数的时候,弄了个副本给函数折腾,于是,从函数返回后,值还是5。嗯,本来应该弄个堆栈图出来的,可是,图是在太难画,因此,我偷懒,用VS2008的调试监视器看看: 
    
    (2)按引用传递值类型 
    初始值还是5,这次换了个传递参数的方式——按引用传递,这次可不是副本了,而是原始值(的地址),这就类似大牌的武打演员总不能老是使用替身一样,偶尔还是要亲自上阵的。既然是亲自上阵,那么,值被修改为10就不足为奇了。正如结果图所示,n=10了。 
    
    (3)按值传递引用类型 和 按引用传递引用类型 
    之所以把这两个放在一起讲,是因为,如结果图所示,两种传递方式,都成功修改了值——这两个函数都分别调用了一个辅助修改的函数Change,去修改内部状态,即m_x,m_y的值,从5到10。呃,竟然都可以成功修改原始值,那么,为什么会存在两种方式呢?它们有什么区别吗?分别用在什么地方?为了说明他们的区别,我特意写了两个名为other的函数,在函数内new一个Point对象,并使从参数传递过来的引用这个新生成的Point对象。值得提醒的是,这个引用其定义在函数体外。其运行如上图我用方框框起来那个。 
    可以很清楚地看到,通过值传递方式,可以改变其值,却不能改变其本身所引用的对象;而按引用传递方式可以。

顺便提一下,代码中,有一段注释掉的代码,使用out关键字的。当你尝试将其两者一起写着,然后,编译,C#编译器是会提示错误的(error CS0663: 'foo' cannot define overloaded methods that differ only on ref and out)。其原因是,C#编译器,对ref和out生成的IL代码,是相同的;而在CLR层面,是没有ref和out的区别的。C#中,ref和out的区别,主要是,谁负责初始化这个参数使之能用——ref形式是函数外初始化,而out是函数内初始化。 
转自:http://www.cnblogs.com/DonLiang/archive/2008/02/16/1070717.html

C# - 函数参数的传递的更多相关文章

  1. 你好,C++(26)如何与函数内部进行数据交换?5.1.3 函数参数的传递

    5.1.3  函数参数的传递 我们知道,函数是用来完成某个功能的相对独立的一段代码.函数在完成这个功能的时候,往往需要外部数据的支持,这时就需要在调用这个函数时向它传递所需要的数据它才能完成这个功能获 ...

  2. C语言函数参数的传递详解

    一.三道考题 开讲之前,我先请你做三道题目.(嘿嘿,得先把你的头脑搞昏才行--唉呀,谁扔我鸡蛋?)考题一,程序代码如下:void Exchg1(int x, int y){   int tmp;    ...

  3. python 函数参数的传递(参数带星号的说明) 元组传递 字典传递

    python中函数参数的传递是通过赋值来传递的.函数参数的使用又有俩个方面值得注意:1.函数参数是如何定义的 2.在调用函数的过程中参数是如何被解析 先看第一个问题,在python中函数参数的定义主要 ...

  4. python 函数参数的传递(参数带星号的说明)

    python中函数参数的传递是通过赋值来传递的.函数参数的使用又有俩个方面值得注意:1.函数参数是如何定义的 2.在调用函数的过程中参数是如何被解析 先看第一个问题,在python中函数参数的定义主要 ...

  5. python函数参数的传递、带星号参数的传递

    python中函数参数的传递是通过赋值来传递的.函数参数的使用又有俩个方面值得注意:1.函数参数是如何定义的 2.在调用函数的过程中参数是如何被解析 先看第一个问题,在python中函数参数的定义主要 ...

  6. Summary: Java中函数参数的传递

    函数调用参数传递类型(java)的用法介绍. java方法中传值和传引用的问题是个基本问题,但是也有很多人一时弄不清. (一)基本数据类型:传值,方法不会改变实参的值. public class Te ...

  7. go语言基础之结构体做函数参数 值传递和地址传递

    1.结构体做函数参数值传递 示例: package main //必须有个main包 import "fmt" //定义一个结构体类型 type Student struct { ...

  8. python中的函数参数的传递

    转载自: http://winterttr.me/2015/10/24/python-passing-arguments-as-value-or-reference/ 我想,这个标题或许是很多初学者的 ...

  9. C语言中将二维数组作为函数参数来传递

    c语言中经常需要通过函数传递二维数组,有三种方法可以实现,如下: 方法一, 形参给出第二维的长度. 例如: #include <stdio.h> void func(int n, char ...

随机推荐

  1. IT经理,你在这个位置吗

    事实上我离这个位置还远着,或者说它可能并不是我以后的方向,但是作为一个码农,这个发展路线还是需要了解的.主要的还是喜欢下面这个图,因为里面我的发展方向,有我的目标. 对 于一个IT从业者,让你谋得工作 ...

  2. 【转载】ACM总结——dp专辑

    感谢博主——      http://blog.csdn.net/cc_again?viewmode=list       ----------  Accagain  2014年5月15日 动态规划一 ...

  3. C# 一次查询多表,填充DataSet并指定表名

    lhrhi 原文 NET 一次查询多表,填充DataSet并指定表名(DataSet指定DataTable名称的技巧) 现实中的场景,有时可能需要一次查询数据库中表张.在使用SqlDataAdapte ...

  4. Selenium2Library系列 keywords 之 _SelectElementKeywords 之 get_selected_list_label(self, locator)

    def get_selected_list_label(self, locator): """Returns the visible label of the selec ...

  5. bzoj 3884 上帝与集合的正确用法(递归,欧拉函数)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=3884 [题意] 求2^2^2… mod p [思路] 设p=2^k * q+(1/0) ...

  6. 一起刷LeetCode3-Longest Substring With Repeating Characters

    拖延症太严重了TAT,真心要处理一下这个问题了,感觉很不好! --------------------------------------------------------------------- ...

  7. Python之Tkinter模块学习

    本文转载自:http://www.cnblogs.com/kaituorensheng/p/3287652.html Tkinter模块("Tk 接口")是Python的标准Tk ...

  8. Hierarchical cluster算法介绍

    突然想记录几个聚类算法,由于实力有限就先介绍一下层次聚类算法(Hierarchical cluster algorithm),这个聚类算法思想简单,但实现起来感觉复杂度挺大:以前看过<集体智慧编 ...

  9. 用Gitolite 构建 Git 服务器

    转载 Gitolite 构建 Git 服务器 作者: 北京群英汇信息技术有限公司 网址: http://www.ossxp.com/ 版本: 0.1-1 日期: 2010-10-07 14:52:19 ...

  10. UVALive 7334 Kernel Knights (dfs)

    Kernel Knights 题目链接: http://acm.hust.edu.cn/vjudge/contest/127407#problem/K Description Jousting is ...