Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

หาขนาดตัวแปรโดยไม่ใช้ sizeof ใน C#

ภาพรวม

ใน C# ใช้ sizeof ได้เฉพาะใน unsafe context สำหรับ primitive types วิธีปลอดภัยคือใช้ BitConverter.GetBytes แปลงค่าเป็น byte array แล้ววัด Length

โค้ดตัวอย่าง


using System;

class Demo {
    public static void Main() {
        int x = 42;

        // ใช้ sizeof (ต้องเป็น unsafe context สำหรับบาง type)
        unsafe {
            int size1 = sizeof(int);
            Console.WriteLine($"sizeof(int) = {size1}");
        }

        // ไม่ใช้ sizeof - ใช้ BitConverter
        byte[] bytes = BitConverter.GetBytes(x);
        int size2 = bytes.Length;
        Console.WriteLine($"BitConverter.GetBytes(int).Length = {size2}");

        // ทดสอบกับ type อื่นๆ
        TestSize(123L);        // long
        TestSize(3.14f);       // float
        TestSize(3.14);        // double
        TestSize(true);        // bool
        TestSize('A');         // char
        TestSize("hello");     // string (reference)
    }

    static void TestSize<T>(T value) where T : struct {
        byte[] bytes = BitConverter.GetBytes(value);
        Console.WriteLine($"sizeof({typeof(T).Name}) = {bytes.Length} bytes");
    }
}

ผลลัพธ์


sizeof(int) = 4
BitConverter.GetBytes(int).Length = 4
sizeof(long) = 8 bytes
sizeof(float) = 4 bytes
sizeof(double) = 8 bytes
sizeof(bool) = 1 bytes
sizeof(char) = 2 bytes

ขนาดของ Primitive Types ใน C#

TypeSize (bytes)Range
bool1true/false
byte / sbyte10-255 / -128 to 127
short / ushort2-32,768 to 32,767 / 0-65,535
int / uint4±2.14B / 0-4.29B
long / ulong8±9.22E18 / 0-1.84E19
float4~±1.5e−45 to ±3.4e38
double8~±5.0e−324 to ±1.7e308
decimal16±1.0e−28 to ±7.9e28
char2UTF-16 code unit

หมายเหตุสำคัญ

  • BitConverter.GetBytes ทำงานได้กับ value types (struct) เท่านั้น
  • สำหรับ reference types (class, string, array) จะได้ขนาดของ reference (4 หรือ 8 bytes ขึ้นอยู่กับ platform)
  • Marshal.SizeOf<T>() ใช้สำหรับ interop/unmanaged memory layout
  • ใน unsafe context: sizeof(MyStruct) ใช้ได้กับ struct ที่ไม่มี reference fields