sizeof() 没有采用我的类型名称

sizeof() not taking my type name

我的程序中有一个 struct,我需要使用它的大小来为结构的一个实例分配托管内存。我尝试使用 sizeof(),但出现以下错误:

Cannot take the address of, get the size of, or declare a pointer to a managed type('StatusType')

'StatusType' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.RunTime.InteropServices.Marshal.SizeOf)

为什么会这样?我正确地使用了 sizeof()(在类型名称上)。使用 Marshal.SizeOf() 是不正确的,因为我没有使用非托管代码。正确的做法是什么?

我的struct如下:

[StructLayout(LayoutKind.Sequential)]
struct StatusType 
{
    ushort VehID;         
    ushort Location;        
    ushort Destination;     

    // Note: the way Intel Byte-swaps, the 16-bit definition below is "backwards" from the way a human may view things
    [FlagsAttribute]
    enum firstByte : uint
    {
        Battery = 2,           
        Reverse = 1,           
        LiveDINO = 1,         
        ActuallyCharging = 1,  
        BothLoads = 2,         
        AttemptingToCharge = 1 
    };

    [FlagsAttribute]
    enum secondByte : uint
    {
        Manual = 1,             
        AutoReady = 1,
        Released = 1,
        Unused1 = 1,           
        CVS = 3,              
        RequestStop = 1         
    };
    // End byte-swap note

    [FlagsAttribute]
    enum thirdByte : ushort { CmdParsingError = 8 }; 
    [FlagsAttribute]
    enum fourthByte : ushort { Error = 8 };       

    [FlagsAttribute]
    enum fifthByte : ushort
    {
        TagReadCycles = 4,                           
        Unused = 4
    };

    [FlagsAttribute]
    enum sixthByte : ushort { Condition = 8 };       

    byte[] Tag;
    ushort CCUInputs;

    [StructLayout(LayoutKind.Sequential)]
    struct union
    {
        ushort ShortCheckSum;   
        ushort DestParam;       
    }

    ushort CurrentLiftHeight;
    ushort PCLInputs;

    [FlagsAttribute]
    enum seventhByte : ushort
    {
        Unused2 = 8             
    };

    [FlagsAttribute]
    enum eigthByte : ushort
    {
        BatteryVoltage = 6,    
        Unused3 = 2
    };

    ushort LongCheckSum;       
}

我想 byte[] Tag; 是你的问题。看看this MSDN article.

尤其是这句话:

One-dimensional arrays of blittable types, such as an array of integers. However, a type that contains a variable array of blittable types is not itself blittable.