相当于一个int数组与只有一个int的结构数组所使用的内存?

Nés*_* A. 6 .net c# struct

考虑下一个结构......

struct Cell
{
    int Value;
}
Run Code Online (Sandbox Code Playgroud)

和下一个矩阵定义

var MatrixOfInts = new int[1000,1000];
var MatrixOfCells = new Cell[1000,1000];
Run Code Online (Sandbox Code Playgroud)

哪一个矩阵会占用更少的内存空间?或者它们是等效的(每字节字节数)?

小智 1

两者的大小相同,因为结构体的处理方式与任何其他值类型相同,并在堆中就地分配。

long startMemorySize2 = GC.GetTotalMemory(true);
var MatrixOfCells = new Cell[1000, 1000];
long matrixOfCellSize = GC.GetTotalMemory(true);

long startMemorySize = GC.GetTotalMemory(true);
var MatrixOfInts = new int[1000, 1000];
long matrixOfIntSize = GC.GetTotalMemory(true);

Console.WriteLine("Int Matrix Size:{0}.  Cell Matrix Size:{1}", 
    matrixOfIntSize - startMemorySize, matrixOfCellSize - startMemorySize2);
Run Code Online (Sandbox Code Playgroud)

这里有一些来自 Jeffery Richter 的关于如何分配数组的有趣读物http://msdn.microsoft.com/en-us/magazine/cc301755.aspx