共用方式為


sizeof (C# 參考)

更新:2007 年 11 月

用於取得實值型別的位元組大小。例如,可以取得 int 型別的大小,如下所示:

int intSize = sizeof(int);

備註

sizeof 運算子只適用於實值型別,而不能用在參考型別。

注意事項:

從 C# 2.0 版以後,將 sizeof 套用至基本型別 (Primitive Type) 時,不再需要使用 unsafe 模式。

sizeof 運算子可能無法多載。sizeof 運算子所傳回的值是 int 型別。下表列出的常數值代表特定基本型別的大小。

運算式

結果

sizeof(sbyte)

1

sizeof(byte)

1

sizeof(short)

2

sizeof(ushort)

2

sizeof(int)

4

sizeof(uint)

4

sizeof(long)

8

sizeof(ulong)

8

sizeof(char)

2 (Unicode)

sizeof(float)

4

sizeof(double)

8

sizeof(bool)

1

至於所有其他型別,包括結構 (Struct),sizeof 運算子只能用於 unsafe 程式碼區塊。雖然您可以使用 Marshal.SizeOf 方法,但是這個方法傳回的值不一定等於 sizeof 傳回的值。Marshal.SizeOf 會傳回型別經過封送處理後的大小。sizeof 則傳回經過 Common Language Runtime 配置的大小,包括任何填補。

範例

class MainClass
{
    // unsafe not required for primitive types
    static void Main()
    {
        Console.WriteLine("The size of short is {0}.", sizeof(short));
        Console.WriteLine("The size of int is {0}.", sizeof(int));
        Console.WriteLine("The size of long is {0}.", sizeof(long));
    }
}
/*
Output:
    The size of short is 2.
    The size of int is 4.
    The size of long is 8.
*/

C# 語言規格

如需詳細資料,請參閱 C# 語言規格中的下列章節:

  • 18.5.8 sizeof 運算子

請參閱

概念

C# 程式設計手冊

參考

C# 關鍵字

運算子關鍵字 (C# 參考)

其他資源

C# 參考