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

Chuyển đổi kiểu (Type Conversion) vs Ép kiểu (Type Casting) trong C#

Trong C#, thuật ngữ "type conversion" và "type casting" thường dùng thay thế nhau, nhưng về mặt kỹ thuật có nuance:

  • Type Conversion: Khái niệm chung - chuyển giá trị từ kiểu này sang kiểu khác.
  • Type Casting (Ép kiểu): Cụ thể chỉ explicit conversion (ép tường minh) dùng toán tử (Type).

2 dạng chuyển đổi

1. Implicit Conversion (Chuyển đổi ngầm / Widening)

An toàn, không mất dữ liệu, không cần cú pháp đặc biệt. Compiler tự chèn.

int i = 10;
long l = i;           // int → long (luôn an toàn)
double d = i;         // int → double
float f = l;          // long → float (có thể mất precision)
Derived d = new Derived();
Base b = d;           // Derived → Base (upcast)

2. Explicit Conversion / Casting (Ép kiểu tường minh / Narrowing)

Có thể mất dữ liệu, ném exception, hoặc invalid. Cần toán tử (Type).

double d = 9322.46;
int i = (int)d;       // 9322 - CẮT phần thập phân (truncation)

long big = 3_000_000_000;
int small = (int)big; // Overflow! Ném OverflowException (checked context) hoặc wrap (unchecked)

Base b = new Derived();
Derived d = (Derived)b; // Downcast - ném InvalidCastException nếu b không phải Derived

Ví dụ: Ép double sang int

using System;

class Program
{
    static void Main()
    {
        double d = 9322.46;
        int i = (int)d; // Ép kiểu tường minh
        Console.WriteLine($"double: {d} → int: {i}"); // 9322
        
        // Kiểm tra overflow (checked context)
        long big = long.MaxValue;
        try
        {
            checked { int x = (int)big; } // Ném OverflowException
        }
        catch (OverflowException)
        {
            Console.WriteLine("Overflow khi ép long → int");
        }
        
        // Convert class (Parse/TryParse) - không phải casting
        string s = "123";
        int parsed = int.Parse(s); // 123
        bool ok = int.TryParse("abc", out int result); // false, result=0
    }
}

Kết quả

double: 9322.46 → int: 9322
Overflow khi ép long → int

Các cách chuyển đổi khác

Phương phápVí dụDùng khi
Casting (T)(int)dKiểu liên quan (numeric, inheritance), chấp nhận rủi ro
Convert.ToType()Convert.ToInt32(d)Chuyển đổi có rounding (Banker's rounding), null→0
Type.Parse/TryParseint.Parse("123")String → Primitive
ToString()i.ToString()Bất kỳ → String
User-defined conversionoperator int(MyStruct)Kiểu tự định nghĩa
as / isobj as stringReference type downcast an toàn (trả null nếu sai)

Tóm tắt

  • Implicit: An toàn, tự động (widening, upcast).
  • Explicit (Cast): Cần (Type), có thể mất data/throw (narrowing, downcast).
  • Convert/Parse: Cho string ↔ primitive, có logic rounding/validation.
  • as/is: Pattern matching an toàn cho reference types.