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

Lấy TypeCode của kiểu giá trị Int32 trong C#

Khái niệm

TypeCode là enum đại diện cho kiểu dữ liệu cơ bản (primitive) trong .NET. Phương thức GetTypeCode() của int (Int32) luôn trả về TypeCode.Int32.

Ví dụ 1: Kiểm tra TypeCode của hai biến int

using System;

public class Demo
{
    public static void Main()
    {
        int val1 = 100;
        int val2 = 50;

        Console.WriteLine($"Value1 = {val1}");
        Console.WriteLine($"Value2 = {val2}");
        Console.WriteLine($"Are they equal? = {val1.Equals(val2)}");
        Console.WriteLine($"HashCode Value1 = {val1.GetHashCode()}");
        Console.WriteLine($"HashCode Value2 = {val2.GetHashCode()}");

        TypeCode type1 = val1.GetTypeCode();
        TypeCode type2 = val2.GetTypeCode();

        Console.WriteLine($"TypeCode Value1 = {type1}");
        Console.WriteLine($"TypeCode Value2 = {type2}");
    }
}

Kết quả

Value1 = 100
Value2 = 50
Are they equal? = False
HashCode Value1 = 100
HashCode Value2 = 50
TypeCode Value1 = Int32
TypeCode Value2 = Int32

Ví dụ 2: TypeCode của giá trị nhỏ và MaxValue

using System;

public class Demo
{
    public static void Main()
    {
        int val1 = 5;
        int val2 = Int32.MaxValue; // 2147483647

        Console.WriteLine($"Value1 = {val1}");
        Console.WriteLine($"Value2 = {val2}");

        TypeCode type1 = val1.GetTypeCode();
        TypeCode type2 = val2.GetTypeCode();

        Console.WriteLine($"TypeCode Value1 = {type1}");
        Console.WriteLine($"TypeCode Value2 = {type2}");
    }
}

Kết quả

Value1 = 5
Value2 = 2147483647
TypeCode Value1 = Int32
TypeCode Value2 = Int32

Ứng dụng thực tế

  • Kiểm tra kiểu tại runtime trong code generic/reflection.
  • Chuyển đổi kiểu động (ví dụ: serialize/deserialize).
  • Switch trên TypeCode thay vì chuỗi tên kiểu.

Bảng TypeCode phổ biến

Kiểu C#TypeCode
boolBoolean
byteByte
charChar
decimalDecimal
doubleDouble
shortInt16
intInt32
longInt64
sbyteSByte
floatSingle
stringString
ushortUInt16
uintUInt32
ulongUInt64