//以下三个结构 public struct myStruct
{
public long lval;
public int ival;
} public struct myStruct1
{
public long lval;
public int ival;
public string str;
} public struct myStruct2
{
public long lval;
public int ival;
public object obj;
} public struct myStruct3
{
public long lval;
public int ival;
public string str;
public object obj;
} class Program
{
static void Main(string[] args)
{
int size;
size = sizeof(int);//返回4
Console.WriteLine("int 型变量占用" + size.ToString() + "字节");
size = sizeof(long);//返回8
Console.WriteLine("long 型变量占用" + size.ToString() + "字节");
unsafe
{
size = sizeof(myStruct); //据说是存在 字节对齐,所以结果为16
}
Console.WriteLine("myStruct 型变量占用" + size.ToString() + "字节"); //Marshal.SizeOf 获取已封送处理类型后的大小,而sizeof返回CLR分配的大小
size = System.Runtime.InteropServices.Marshal.SizeOf(new myStruct());//返回16,why?
Console.WriteLine("Marshal.SizeOf方法获得的myStruct占用" + size + "字节");
//why1??????????????
size = System.Runtime.InteropServices.Marshal.SizeOf(new mySturct1()); //返回16
Console.WriteLine("Marshal.SizeOf方法获得的myStruct1占用" + size + "字节"); //why2??????????????????
size = System.Runtime.InteropServices.Marshal.SizeOf(new mySturct2()); //返回16
Console.WriteLine("Marshal.SizeOf方法获得的myStruct2占用" + size + "字节"); //why3??????????????????
size = System.Runtime.InteropServices.Marshal.SizeOf(new mySturct3()); //返回24
Console.WriteLine("Marshal.SizeOf方法获得的myStruct3占用" + size + "字节"); Console.ReadKey();
}
}
问题:为什么why1,why2处返回为16,而why3处返回为24??谢谢!(.NET Framework 3.5)
内存对齐我在网上搜了相关文章,有一点了解!我的问题是
针对这样三个结构: public struct myStruct1
{
public long lval;
public int ival;
public string str;
}//Marshal.SizeOf返回16 public struct myStruct2
{
public long lval;
public int ival;
public object obj;
}//Marshal.SizeOf依然返回16 public struct myStruct3
{
public long lval;
public int ival;
public string str;
public object obj;
}//关键这里,为什么一下子成了24了,按上面两个的结果看应该也是16才对,为什么呢?
使用Marshal.SizeOf方法后返回的结果怎么是16,16,24
struct3
------------
long : 8
int : 4
string : 4
object : 4
------------
超过16了。