作者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://webptt.com/cn.aspx?n=bbs/Programming/M.1420528502.A.417.html
※ 编辑: jamod (60.249.2.10), 01/06/2015 15:19:06
1F:→ fireslayer: 用class来包就可以了140.113.170.177 01/06 17:19
2F:→ fireslayer: 因为Struct是value type,class是ref140.113.170.177 01/06 17:23
3F:→ fireslayer: type140.113.170.177 01/06 17:23
4F:→ jamod: 恩~感谢你的解决方法 60.249.2.10 01/07 09:01
5F:→ Killercat: 最简单的做法就是 不知道struct干嘛的 59.124.251.135 01/07 15:26
6F:→ Killercat: 话 不要用struct 59.124.251.135 01/07 15:26
7F:→ Killercat: 绝大多数的情况用class都是正确的 59.124.251.135 01/07 15:26