sizeof 運算子 - 會判斷指定類型的記憶體需求

sizeof 運算子會返回指定型別變數所佔用的位元組總數。 sizeof 運算子的引數必須是非受控型別的名稱,或是限制為非受控型別的型別參數。

sizeof 運算子需要 unsafe 內容。 但是,下表顯示的運算式會在編譯時評估至對應的常數值,因此不需要 unsafe 內容:

運算式 常數值
sizeof(sbyte) 1
sizeof(byte) 7
sizeof(short) 2
sizeof(ushort) 2
sizeof(int) 4
sizeof(uint) 4
sizeof(long) 8
sizeof(ulong) 8
sizeof(char) 2
sizeof(float) 4
sizeof(double) 8
sizeof(decimal) 16
sizeof(bool) 1

您也不需要在 sizeof 運算子的運算元是 enum 型別時使用 unsafe 內容。

下列範例示範 sizeof 運算子的用法:

public struct Point
{
    public Point(byte tag, double x, double y) => (Tag, X, Y) = (tag, x, y);

    public byte Tag { get; }
    public double X { get; }
    public double Y { get; }
}

public class SizeOfOperator
{
    public static void Main()
    {
        Console.WriteLine(sizeof(byte));  // output: 1
        Console.WriteLine(sizeof(double));  // output: 8

        DisplaySizeOf<Point>();  // output: Size of Point is 24
        DisplaySizeOf<decimal>();  // output: Size of System.Decimal is 16

        unsafe
        {
            Console.WriteLine(sizeof(Point*));  // output: 8
        }
    }

    static unsafe void DisplaySizeOf<T>() where T : unmanaged
    {
        Console.WriteLine($"Size of {typeof(T)} is {sizeof(T)}");
    }
}

sizeof 運算子會傳回通用語言執行平台在受控記憶體中原先將配置的位元組數。 針對 struct型別,該值包含任何填補,如先前範例所示範。 sizeof 運算子的結果可能會與 Marshal.SizeOf 方法的結果不同,因為後者會傳回型別在 unmanaged 記憶體中的大小。

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格中的 sizeof 運算子區段。

另請參閱