请查看以下代码:
unsafe
{
byte by = 1; // 1 byte
short sh = 1; // 2 bytes
int it = 1; // 4 bytes
double dou = 1; //8 bytes
byte* byP = &by;
short* shP = &sh;
int* itP = ⁢
double* douP = &dou;
IntPtr add = (IntPtr)byP;
IntPtr add2 = (IntPtr)shP;
IntPtr add3 = (IntPtr)itP;
IntPtr add4 = (IntPtr)douP;
Console.WriteLine(Marshal.SizeOf(by) + " " + Marshal.SizeOf(sh) + " " + Marshal.SizeOf(it) + " " + Marshal.SizeOf(dou));
Console.WriteLine(add.ToString() + " " + add2.ToString() + " " + add3.ToString() + " " + add4.ToString());
//output:
//1 2 4 8
//--------------------------------------------------------------------
//6943624 6943620 6943616 6943608
}
我无法理解为什么 short 或 byte 这样的类型在RAM中保留4个字节的内存,如果 short 需要2个字节且 byte 只需要1个字节吗?有人可以向我解释一下吗?