日期:2014-05-19  浏览次数:21115 次

结构体中byte类型数据的长度会变化?
遇到一个问题:
        public   unsafe   struct   testStruct
        {
//                 public   fixed   char   Name[5];
                public   byte   Type;
//                 public   uint   ID;
//                 public   ushort   Value;
        };
int   size=sizeof(testStruct);
此时size=1;

        public   unsafe   struct   testStruct
        {
//                 public   fixed   char   Name[5];
                public   byte   Type;
//                 public   uint   ID;
                public   ushort   Value;
        };
int   size=sizeof(testStruct);
此时size=4;

        public   unsafe   struct   testStruct
        {
//                 public   fixed   char   Name[5];
                public   byte   Type;
                public   uint   ID;
//                 public   ushort   Value;
        };
int   size=sizeof(testStruct);
此时size=8;

        public   unsafe   struct   testStruct
        {
                public   fixed   char   Name[5];
                public   byte   Type;
//                 public   uint   ID;
//                 public   ushort   Value;
        };
int   size=sizeof(testStruct);
此时size=12;

请教各位这是怎么回事?byte的长度能变化?怎么样才能使它总为1呢?
谢谢!



------解决方案--------------------
public unsafe struct testStruct
{
// public fixed char Name[5];
public byte Type;
// public uint ID;
// public ushort Value;
};
只有byte,因此为1
public unsafe struct testStruct
{
// public fixed char Name[5];
public byte Type;
// public uint ID;
public ushort Value;
};
byte和ushort,产生补位.在byte后会再加一位,使ushort的地址能被2整除.因此为4.
其它雷同,
public unsafe struct testStruct
{
// public fixed char Name[5];
public byte Type;
public uint ID;
// public ushort Value;
};
会在byte后补3位,使unit的地址能被4整除.

public unsafe struct testStruct
{
public fixed char Name[5];
public byte Type;
// public uint ID;
// public ushort Value;
};
这个不太清楚,呵呵
byte一直是1,你这些情况只是struct的对齐问题.LZ可以看看相关的知识