在这里讨论了SO之后,我已经多次读过可变结构是"邪恶"的评论(就像这个问题的答案一样).
C#中可变性和结构的实际问题是什么?
我正在写一个拥有巨大2D"细胞"阵列的游戏.一个单元只需3个字节.我还有一个名为CellMap的类,它包含2D数组作为私有字段,并通过公共索引器提供对它的访问.
Profiling showed that a performance problem is caused by garbage collection of too many Cell objects. So I decided to make Cell a struct (it was a class).
But now code like this doesn't work:
cellMap[x, y].Population++;
Run Code Online (Sandbox Code Playgroud)
I can think of many options, but I don't really like any of them.
cellMap.Data[x, y].Population = 5;