Giới thiệu
Phương thức GetTypeCode() của struct Decimal trả về enum TypeCode.Decimal. Đây là cách chuẩn để xác định kiểu runtime của một giá trị Decimal.
Ví dụ 1: TypeCode của Decimal.MaxValue
using System;
public class Demo
{
public static void Main()
{
Decimal val = Decimal.MaxValue;
Console.WriteLine("Decimal Value = {0}", val);
Console.WriteLine("HashCode = {0}", (val.GetHashCode()));
TypeCode type = val.GetTypeCode();
Console.WriteLine("TypeCode = " + type);
}
}
Kết quả
Decimal Value = 79228162514264337593543950335 HashCode = 1173356544 TypeCode = Decimal
Ví dụ 2: TypeCode của giá trị Decimal thường
using System;
public class Demo
{
public static void Main()
{
Decimal val = 3972.491M;
Console.WriteLine("Decimal Value = {0}", val);
Console.WriteLine("HashCode = {0}", (val.GetHashCode()));
TypeCode type = val.GetTypeCode();
Console.WriteLine("TypeCode = " + type);
}
}
Kết quả
Decimal Value = 3972.491 HashCode = 620041307 TypeCode = Decimal
Các giá trị TypeCode phổ biến
| TypeCode | Kiểu .NET | Từ khóa C# |
|---|---|---|
| Boolean | System.Boolean | bool |
| Byte | System.Byte | byte |
| Char | System.Char | char |
| DateTime | System.DateTime | DateTime |
| Decimal | System.Decimal | decimal |
| Double | System.Double | double |
| Int16 | System.Int16 | short |
| Int32 | System.Int32 | int |
| Int64 | System.Int64 | long |
| String | System.String | string |
Ứng dụng thực tế
public static void ProcessValue(object value)
{
switch (Type.GetTypeCode(value.GetType()))
{
case TypeCode.Decimal:
Console.WriteLine("Xử lý tiền tệ: " + value);
break;
case TypeCode.Int32:
Console.WriteLine("Xử lý số nguyên: " + value);
break;
// ...
}
}