看板C_Sharp
标 题Re: [问题] passing parameters
发信站BalaBBS (Sun Jan 16 02:46:19 2005)
转信站ptt!ctu-reader!ctu-peer!news.nctu!news.csie.ncyu!news.ncyu!news.ccu!ne
我想是因为在Entrance中 "a1.Add(2)", 就会修改到Main中的a1
另外, 去查了一下MSDN有关passing Parameters的部份(网址
http://tinyurl.com/1zdn)
A variable of a reference type does not contain its data directly; it
contains a reference to its data. When you pass a reference-type parameter by
value, it is possible to change the data pointed to by the reference, such as
the value of a class member. However, you cannot change the value of the
reference itself; that is, you cannot use the same reference to allocate
memory for a new class and have it persist outside the block. To do that,
pass the parameter using the ref (or out) keyword. For simplicity, the
following examples use ref.
里面有提到没用ref(or out) modifier是没办法修改所传进去的reference本身的值
所以我想在Entrance中
"a2 = local;"
应该是不能这样写
有错请各位先进赐教 谢谢
※ 引述《[email protected] (hmmm)》之铭言:
> 我们知道在C# 当我们传参数到一个method时, 若传的参数是value type,
> 则他会在method中有个temporary copy, 所以我们若是想要真正的改变传
> 进去的参数值一定要加ref这个modifier.
> 那请问各位, reference type的状况到底是如何?
> 我自己写了几个不同的传reference type的method来测试, 可是还是不太
> 懂他的机制, 请各位解惑一下
> private static void Entrance(ArrayList a1, ArrayList a2, ref ArrayList a3)
> {
> ArrayList local = new ArrayList();
> a1.Add(2);
> a1.Add(3);
> local.Add(3);
> local.Add(4);
> a2 = local;
> a3 = local;
> }
> static void Main(string[] args)
> {
> ArrayList a1 = new ArrayList(), a2 = new ArrayList(), a3 = new ArrayList();
> Entrance(a1, a2, ref a3);
> }
> 结果
> a1 2,3
> a2 没东西
> a3 3,4
> 根据a2, a3的结果我推论reference type也是传一个copy进去,
> 但是如果是这样的话, 那a1也应该是空的, 但结果a1中有两个element
> 有人可以帮我解答这问题吗?
--
◥◣ │◢ 我说拔辣!!◣╭─────────╮ ◢香蕉!!◣ \ ◢◤ˋ
ˋ ˊ▊ ●◤◥ ◤│ IP:140.123.174.1▂▃▅▆▇ ◥ ◤◥ ● ▊"
ˊ
" " ▋╯ ▁▃ DN:bala.twbbs.org│ ╰◢◤ "
∵ ∵▌▂▃▄▅▆▇█ ╰─────────╯《中正资管‧芭乐的故乡》 ▋!
!◢◤ FR: 218-165-120-27.dynamic.hinet.net ◢◤ ◢
◆ Modify: 05/01/16 2:46:19 <218-165-120-27.dynamic.hinet.net>