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

Lớp Convert trong C#

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ứcMô tả
ToBooleanChuyển sang bool
ToByte / ToSByteChuyển sang byte (unsigned/signed)
ToCharChuyển sang char (chuỗi 1 ký tự)
ToDateTimeChuyển sang DateTime
ToDecimalChuyển sang decimal (tiền tệ, chính xác)
ToDouble / ToSingleChuyển sang double/float
ToInt16 / ToInt32 / ToInt64Chuyển sang short/int/long
ToUInt16 / ToUInt32 / ToUInt64Chuyển sang unsigned
ToStringChuyển object sang string (xử lý null)
ChangeTypeChuyể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ểmConvert.ToXxxType.ParseType.TryParse
Null inputTrả về mặc định (0, false...)Throw ArgumentNullExceptionTrả về false, out = default
Invalid formatThrow FormatExceptionThrow FormatExceptionTrả về false
OverflowThrow OverflowExceptionThrow OverflowExceptionTrả về false
IFormatProviderCóCóCó
Hiệu năngTrung bìnhTrung bìnhTốt nhất (no exception)

Best Practice

  • Dùng TryParse cho input người dùng/file (an toàn, nhanh).
  • Dùng Convert khi chắc chắn dữ liệu hợp lệ hoặc cần xử lý null -> default.
  • Luôn chỉ định CultureInfo.InvariantCulture cho parsing chuẩn (file, network).