Re: [問題] passing parameters

看板C_Sharp (C#)作者時間20年前 (2005/01/17 02:01), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
我想是因為在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;" 應該是不能這樣寫 有錯請各位先進賜教 謝謝 ※ 引述《phe.bbs@ptt.cc (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>
文章代碼(AID): #11wgle00 (C_Sharp)
文章代碼(AID): #11wgle00 (C_Sharp)