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 đủ
| TypeCode | Kiểu C# | CLR Type |
|---|---|---|
| Empty | - | null reference |
| Object | object | System.Object |
| DBNull | - | System.DBNull |
| Boolean | bool | System.Boolean |
| Char | char | System.Char |
| SByte | sbyte | System.SByte |
| Byte | byte | System.Byte |
| Int16 | short | System.Int16 |
| UInt16 | ushort | System.UInt16 |
| Int32 | int | System.Int32 |
| UInt32 | uint | System.UInt32 |
| Int64 | long | System.Int64 |
| UInt64 | ulong | System.UInt64 |
| Single | float | System.Single |
| Double | double | System.Double |
| Decimal | decimal | System.Decimal |
| DateTime | DateTime | System.DateTime |
| String | string | System.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
IConvertiblemớ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.