作者jamod (jasper)
看板Programming
標題[問題] C#的一個List和Array的問題
時間Tue Jan 6 15:14:59 2015
應該是有關記憶體的問題,但上網找了一些說明,還是不是很了解
=============================================
public struct s_Test{
public int i;
}
上面是我自訂的一個struct
=======================================================
s_Test t = new s_Test();
List<s_Test> list = new List<s_Test>();
list.Add(t);
list[0].i = 10;
當我用上面的方法修改list[0].i的值會出錯,
看說明是叫我new一個新的struct直接覆蓋list[0]
所以我改成:
===========================================================
List<s_Test> list = new List<s_Test>();
list.Add(t);
s_Test temp = new s_Test();
temp.i = 10;
list[0] = temp;
上面這樣才可以變更裡面的值,但是我改成陣列來儲存:
===========================================================
s_Test[] array = new s_Test[10];
array[0] = t;
array[0].i = 10;
就可以直接修改i了,想請問有沒有高手能夠解釋原因?
非常感謝!
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.249.2.10
※ 文章網址: http://www.ptt.cc/bbs/Programming/M.1420528502.A.417.html
※ 編輯: jamod (60.249.2.10), 01/06/2015 15:19:06
→ fireslayer: 用class來包就可以了140.113.170.177 01/06 17:19
→ fireslayer: 因為Struct是value type,class是ref140.113.170.177 01/06 17:23
→ fireslayer: type140.113.170.177 01/06 17:23
→ jamod: 恩~感謝你的解決方法 60.249.2.10 01/07 09:01
→ Killercat: 最簡單的做法就是 不知道struct幹嘛的 59.124.251.135 01/07 15:26
→ Killercat: 話 不要用struct 59.124.251.135 01/07 15:26
→ Killercat: 絕大多數的情況用class都是正確的 59.124.251.135 01/07 15:26