日期:2014-05-17  浏览次数:21047 次

菜鸟纳闷:byte与ushort 问题,见笑了 呵呵
情况如下:
public struc aa

 public byte a;
 public ushort b;
}

测试:
click:
  ushort Len;
  aa a = new aa();  
  Len=(ushort)Marshal.SizeOf(a);// 这里len=4 bytes (按道理应该是3bytes啊 不知道为什么,大侠能否解释下?)

************************************
public struc aa

 //public byte a;
 public ushort b;
}

测试:
click:
  ushort Len;
  aa a = new aa();  
  Len=(ushort)Marshal.SizeOf(a);// 这里len=2 bytes (这里没错) 
***************************
public struc aa

 public byte a;
// public ushort b;
}

测试:
click:
  ushort Len;
  aa a = new aa();  
  Len=(ushort)Marshal.SizeOf(a);// 这里len=1 byte(这里没错)

************************
byte,ushort 组合 就出现了问题,难道是Marshal.SizeOf这个函数不可靠? 求解释

------解决方案--------------------
字节对齐问题
------解决方案--------------------
应该是4字节对齐了。
------解决方案--------------------
大概要加上[StructLayout(LayoutKind.Sequential, Pack = 1)]



------解决方案--------------------
By default the CLR is allowed to rearrange (which for simple structs it never does) and pad structs as it pleases. This is typically to keep it aligned to word boundaries when in memory.

If you don't like this behavior and want to change it, you can specify no packing as follows:

[StructLayout(LayoutKind.Sequential,Pack=1)]

以上来自:
Using Marshal.SizeOf() method on a custom struct containing only value types
http://stackoverflow.com/questions/9220999/using-marshal-sizeof-method-on-a-custom-struct-containing-only-value-types