Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Tìm kích thước biến không dùng sizeof trong C#

Trong C#, sizeof chỉ dùng được trong ngữ cảnh unsafe. Cách an toàn: dùng BitConverter.GetBytes hoặc Marshal.SizeOf.

Ví dụ minh họa

using System;
using System.Runtime.InteropServices;

class Program
{
    static void Main()
    {
        int x = 42;
        
        // Cách 1: BitConverter (chỉ cho primitive types)
        byte[] bytes = BitConverter.GetBytes(x);
        Console.WriteLine($"sizeof(int) qua BitConverter: {bytes.Length} bytes");
        
        // Cách 2: Marshal.SizeOf (cho struct, blittable types)
        int size = Marshal.SizeOf();
        Console.WriteLine($"Marshal.SizeOf(): {size} bytes");
        
        // Cách 3: sizeof trong unsafe context
        unsafe
        {
            Console.WriteLine($"sizeof(int) trong unsafe: {sizeof(int)} bytes");
        }
        
        // Test với struct
        struct Point { public int X, Y; }
        Console.WriteLine($"Kích thước Point struct: {Marshal.SizeOf()} bytes");
    }
}

Kết quả đầu ra

sizeof(int) qua BitConverter: 4 bytes
Marshal.SizeOf(): 4 bytes
sizeof(int) trong unsafe: 4 bytes
Kích thước Point struct: 8 bytes

Lưu ý: BitConverter.GetBytes chỉ dùng cho kiểu giá trị primitive. Marshal.SizeOf dùng cho struct blittable. Kích thước runtime có thể khác compile-time do padding/alignment.