Difference between ref and value

本文探讨了.NET中引用类型通过值传递与引用传递的区别。通过示例代码展示,当使用值传递时,虽然创建了参数副本,但由于指向同一堆内存地址,对对象所做的更改会影响原始对象;而使用引用传递时,则直接操作原始对象。
Difference between passing reference types by ref and by value

A Brief Insight into Reference Types:
Data for Reference types is stored on the heap and a pointer (which points to the data on the heap) is created on the stack, whenever an instance of reference type is created the pointer is returned back and is used to manipulate the data on the stack. Hence Hashtable hst = new HashTable(); actually returns back the pointer. Now when this pointer is passed by val, all we are doing is duplicating the pointer but it still points to the same memory on the heap and hence any manipulation done to the object in the called method will manipulate the same data to which original hashtable pointer was pointing. In case of passing by ref, the original pointer itself is passed to the called function. 

So what is the difference between passing byref v/s passing byval? Lets take a look at the slightly modified version of above code:
static void Main()
{
Hashtable hst = new Hashtable(3);
hst.Add(1,1);
PassHashTableByVal(hst); //by default .net parameters are passed by val
Console.WriteLine("Count after passing byval: {0}",hst.Count); //will print 2
PassHashTableByRef(ref hst);
Console.WriteLine(揅ount after passing byref: {0}? hst.Count); //will throw a null reference exception.
Console.Read();
}

static void PassHashTableByVal(Hashtable h1)
{
h1.Add(2,2);
h1 = null;
}

static void PassHashTableByRef(ref Hashtable h2)
{
h2.Add(3,3);
h2 = null;
}

转载于:https://www.cnblogs.com/dotrai/archive/2006/03/02/341536.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值