今天在看discuz!nt 源代码的时候,一些地方用到了ref关键字,由于平时很少接触这东西,略感疑惑,于是在MSDN上找到了答案,挺有意思的,以下摘抄自MSDN:
ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。
简单的说就是:通常在值传递时,只是传递的对象的副本,对副本的操作,不能影响到对象本身,而 加上REF关键字后,所做的任何修改,都捡影响到对象本身.
Code
1public partial class Ref_Default : System.Web.UI.Page
2{
3 protected void Page_Load(object sender, EventArgs e)
4 {
5 int oldInt = 10;
6 TestRef(ref oldInt);
7 Response.Write(oldInt.ToString());
8 }
9
10 public void TestRef(ref int newInt)
11 {
12 newInt = 20;
13 }
14}
15
1public partial class Ref_Default : System.Web.UI.Page
2{
3 protected void Page_Load(object sender, EventArgs e)
4 {
5 int oldInt = 10;
6 TestRef(ref oldInt);
7 Response.Write(oldInt.ToString());
8 }
9
10 public void TestRef(ref int newInt)
11 {
12 newInt = 20;
13 }
14}
15
这段代码最后输出的会是20
转载于:https://www.cnblogs.com/tufan/archive/2009/04/19/1439111.html