An toàn kiểu (Type Safety)
Quá trình chuyểu đổi kiểu (Type Conversions)
Chúng ta thường chuyển đổi dữ liệu từ một kiểu sang kiểu khác thí dụ sau:
byte value1 = 10;
byte value2 = 23;
byte total;
total = value1 + value2;
Console.WriteLine(total);
Implicit Conversions
Chúng ta sẽ không có vấn đề gì khi thực hiện đoạn mã sau:
byte value1 = 10;
byte value2 = 23;
long total; // đoạn sau sẽ biên dịch tốt
total = value1 + value2;
Console.WriteLine(total);
Bảng sau hiển thị cách chuyển đổi kiểu implicit được hỗ trợ trong C#.
From To
sbyte short, int, long, float, double, decimal
byte short, ushort, int, uint, long, ulong, float, double, decimal
short int, long, float, double, decimal
ushort int, uint, long, ulong, float, double, decimal
int long, float, double, decimal
uint long, ulong, float, double, decimal
long, ulong float, double, decimal
float double
char ushort, int, uint, long, ulong, float, double, decimal
Explicit Conversions
•
int to short – Có thể mất dữ liệu
Đoạn code sau sử dụng Unboxing , o thuộc kiểu đối tượng object được chuyể
n thành j
kiểu int.
int i = 20;
object o = i; // Box the int
int j = (int)o; // Unbox it back into an int
ví dụ sau dùng Boxing và Unboxing
long a = 333333423;
object b = (object)a;
int c = (int)b;