sizeof() structures not known. Why?

前端 未结 1 770
面向向阳花
面向向阳花 2020-12-06 09:40

Why can\'t I use sizeof() on simple structs?

eg:

private struct FloatShortPair
{
    public float myFloat;
    public short myShort;
};

int size = s         


        
相关标签:
1条回答
  • 2020-12-06 10:04

    The sizes of short and float are constant - but how the CLR decided to pack that float in memory isn't necessarily constant. For example, on a 64-bit processor it may decide to align each value on an 8-byte boundary.

    From the C# 4 spec, section 18.5.8:

    For certain predefined types, the sizeof operator yields a constant value as shown in the table below.

    [...]

    For all other types, the result of the sizeof operator is implementation-defined and is classified as a value, not a constant.

    [...]

    For alignment purposes, there may be unnamed padding at the beginning of a struct, within a struct, and at the end of a struct.

    Note that you can use sizeof in this situation, within an unsafe context. Whether you should use that or Marshal.SizeOf depends on what you're trying to do.

    0 讨论(0)
提交回复
热议问题