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

Lấy TypeCode trong C#

Khái niệm

TypeCode là enum đại diện cho các kiểu dữ liệu cơ bản (primitive types) trong .NET. Phương thức GetTypeCode() (triển khai IConvertible) trả về TypeCode của instance.

Ví dụ 1: TypeCode của string

using System;

public class Demo
{
    public static void Main()
    {
        string s = "Demo";
        Console.WriteLine($"String: {s}");
        Console.WriteLine($"GetType(): {s.GetType()}");       // System.String
        Console.WriteLine($"GetTypeCode(): {s.GetTypeCode()}"); // String
    }
}

Kết quả

String: Demo
GetType(): System.String
GetTypeCode(): String

Ví dụ 2: TypeCode của int và double

using System;

public class Demo
{
    public static void Main()
    {
        int i = 100;
        double d = 5.26;

        Console.WriteLine($"Value1: {i}");
        Console.WriteLine($"GetType(): {i.GetType()}");       // System.Int32
        Console.WriteLine($"GetTypeCode(): {i.GetTypeCode()}"); // Int32

        Console.WriteLine($"\nValue2: {d}");
        Console.WriteLine($"GetType(): {d.GetType()}");       // System.Double
        Console.WriteLine($"GetTypeCode(): {d.GetTypeCode()}"); // Double
    }
}

Kết quả

Value1: 100
GetType(): System.Int32
GetTypeCode(): Int32

Value2: 5.26
GetType(): System.Double
GetTypeCode(): Double

Bảng TypeCode đầy đủ

TypeCodeKiểu C#CLR Type
Empty-null reference
ObjectobjectSystem.Object
DBNull-System.DBNull
BooleanboolSystem.Boolean
CharcharSystem.Char
SBytesbyteSystem.SByte
BytebyteSystem.Byte
Int16shortSystem.Int16
UInt16ushortSystem.UInt16
Int32intSystem.Int32
UInt32uintSystem.UInt32
Int64longSystem.Int64
UInt64ulongSystem.UInt64
SinglefloatSystem.Single
DoubledoubleSystem.Double
DecimaldecimalSystem.Decimal
DateTimeDateTimeSystem.DateTime
StringstringSystem.String

Ứng dụng

  • Switch trên TypeCode thay vì type name string (nhanh hơn, type-safe).
  • Serialization: ghi TypeCode trước value.
  • Dynamic conversion: Convert.ChangeType(value, typeCode).
  • Reflection: so sánh Type.GetTypeCode(type).

Ví dụ: Convert.ChangeType với TypeCode


object val = "123";
TypeCode tc = Type.GetTypeCode(val.GetType()); // String
if (tc == TypeCode.String)
{
    int num = (int)Convert.ChangeType(val, TypeCode.Int32); // 123
}

Lưu ý

  • Chỉ các kiểu implement IConvertible mới có GetTypeCode() hợp lệ (primitive + DateTime, String, Decimal).
  • Custom struct/class: GetTypeCode() trả về TypeCode.Object.
  • typeof(int).GetTypeCode() -> cần instance, không dùng trên Type trực tiếp.