sizeof 运算符(C# 参考)sizeof operator (C# reference)

sizeof 运算符返回给定类型的变量所占用的字节数。The sizeof operator returns the number of bytes occupied by a variable of a given type. sizeof 运算符的参数必须是一个非托管类型的名称,或是一个限定为非托管类型的类型参数。The argument to the sizeof operator must be the name of an unmanaged type or a type parameter that is constrained to be an unmanaged type.

sizeof 运算符需要不安全上下文。The sizeof operator requires an unsafe context. 但下表中的表达式在编译时被计算为相应的常数值,并不需要“不安全”的上下文:However, the expressions presented in the following table are evaluated in compile time to the corresponding constant values and don't require an unsafe context:

ExpressionExpression 常量值Constant value
sizeof(sbyte) 11
sizeof(byte) 11
sizeof(short) 22
sizeof(ushort) 22
sizeof(int) 44
sizeof(uint) 44
sizeof(long) 88
sizeof(ulong) 88
sizeof(char) 22
sizeof(float) 44
sizeof(double) 88
sizeof(decimal) 1616
sizeof(bool) 11

下列情况也不需要使用不安全的上下文:sizeof 运算符的操作数是枚举类型的名称。You also don't need to use an unsafe context when the operand of the sizeof operator is the name of an enum type.

下面的示例演示 sizeof 运算符的用法:The following example demonstrates the usage of the sizeof operator:

using System;

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

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

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

sizeof 运算符返回公共语言运行时将在托管内存中分配的字节数。The sizeof operator returns a number of bytes that would be allocated by the common language runtime in managed memory. 对于结构类型,该值包括了填充(如有),如前例所示。For struct types, that value includes any padding, as the preceding example demonstrates. sizeof 运算符的结果可能异于 Marshal.SizeOf 方法的结果,该方法返回某个类型在非托管内存中的大小。The result of the sizeof operator might differ from the result of the Marshal.SizeOf method, which returns the size of a type in unmanaged memory.

C# 语言规范C# language specification

有关详细信息,请参阅 C# 语言规范sizeof 运算符部分。For more information, see The sizeof operator section of the C# language specification.

另请参阅See also