[問題] C#的一個List和Array的問題

看板Programming作者 (jasper)時間10年前 (2015/01/06 15:15), 10年前編輯推噓0(007)
留言7則, 3人參與, 最新討論串1/3 (看更多)
應該是有關記憶體的問題,但上網找了一些說明,還是不是很了解 ============================================= 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

01/06 17:19, , 1F
用class來包就可以了
01/06 17:19, 1F

01/06 17:23, , 2F
因為Struct是value type,class是ref
01/06 17:23, 2F

01/06 17:23, , 3F
type
01/06 17:23, 3F

01/07 09:01, , 4F
恩~感謝你的解決方法
01/07 09:01, 4F

01/07 15:26, , 5F
最簡單的做法就是 不知道struct幹嘛的
01/07 15:26, 5F

01/07 15:26, , 6F
話 不要用struct
01/07 15:26, 6F

01/07 15:26, , 7F
絕大多數的情況用class都是正確的
01/07 15:26, 7F
文章代碼(AID): #1KgujsGN (Programming)
文章代碼(AID): #1KgujsGN (Programming)