Tổng quan
Lớp tĩnh System.Convert cung cấp các phương thức chuyển đổi giữa các **kiểu cơ sở (base types)**: Boolean, Byte, Char, DateTime, Decimal, Double, Int16/32/64, SByte, Single, String, UInt16/32/64. Xử lý null, format provider, overflow.
1. Convert.ToBoolean(string, IFormatProvider)
Chuyển chuỗi thành bool. Chỉ chấp nhận "True"/"False" (case-insensitive) hoặc null (-> false).
using System;
using System.Globalization;
public class Demo
{
public static void Main()
{
CultureInfo ci = new CultureInfo("en-US");
string str = "true";
bool res = Convert.ToBoolean(str, ci);
Console.WriteLine($"Converted bool: {res}"); // True
// Các giá trị hợp lệ: "True", "False", null
// "1", "0", "yes", "no" -> FormatException
}
}
2. Convert.ToDouble(string, IFormatProvider)
Chuyển chuỗi thành double với định dạng tùy chỉnh qua NumberFormatInfo.
using System;
using System.Globalization;
public class Demo
{
public static void Main()
{
string val = "876876, 878"; // Dùng dấu phẩy làm decimal separator
NumberFormatInfo provider = new NumberFormatInfo
{
NumberDecimalSeparator = ",",
NumberGroupSeparator = ".",
NumberGroupSizes = new int[] { 2 } // Nhóm 2 chữ số
};
double res = Convert.ToDouble(val, provider);
Console.WriteLine($"Converted Double: {res}"); // 876876.878
}
}
3. Convert.ToDecimal(string, IFormatProvider)
using System;
using System.Globalization;
public class Demo
{
public static void Main()
{
CultureInfo ci = new CultureInfo("en-US");
string val = "8787";
decimal res = Convert.ToDecimal(val, ci);
Console.WriteLine($"Converted Decimal: {res}"); // 8787
}
}
Bảng phương thức chuyển đổi phổ biến
| Phương thức | Mô tả |
|---|---|
| ToBoolean | Chuyển sang bool |
| ToByte / ToSByte | Chuyển sang byte (unsigned/signed) |
| ToChar | Chuyển sang char (chuỗi 1 ký tự) |
| ToDateTime | Chuyển sang DateTime |
| ToDecimal | Chuyển sang decimal (tiền tệ, chính xác) |
| ToDouble / ToSingle | Chuyển sang double/float |
| ToInt16 / ToInt32 / ToInt64 | Chuyển sang short/int/long |
| ToUInt16 / ToUInt32 / ToUInt64 | Chuyển sang unsigned |
| ToString | Chuyển object sang string (xử lý null) |
| ChangeType | Chuyển đổi động tại runtime |
Xử lý Overflow và Null
// OverflowException nếu giá trị ngoài phạm vi kiểu đích
Convert.ToByte(300); // Throw
// Null handling
Convert.ToInt32(null); // Trả về 0 (không throw)
// Ngược lại: int.Parse(null) -> ArgumentNullException
// Base64
string b64 = Convert.ToBase64String(new byte[] { 1, 2, 3 });
byte[] bytes = Convert.FromBase64String(b64);
Convert vs Parse vs TryParse
| Đặc điểm | Convert.ToXxx | Type.Parse | Type.TryParse |
|---|---|---|---|
| Null input | Trả về mặc định (0, false...) | Throw ArgumentNullException | Trả về false, out = default |
| Invalid format | Throw FormatException | Throw FormatException | Trả về false |
| Overflow | Throw OverflowException | Throw OverflowException | Trả về false |
| IFormatProvider | Có | Có | Có |
| Hiệu năng | Trung bình | Trung bình | Tốt nhất (no exception) |
Best Practice
- Dùng
TryParsecho input người dùng/file (an toàn, nhanh). - Dùng
Convertkhi chắc chắn dữ liệu hợp lệ hoặc cần xử lý null -> default. - Luôn chỉ định
CultureInfo.InvariantCulturecho parsing chuẩn (file, network).