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

Khác biệt giữa implicit và explicit type conversion trong C#


Implicit Type Conversion (Chuyển đổi ngầm)

C# tự động thực hiện an toàn kiểu.

Ví dụ int -> long:

int val1 = 11000, val2 = 35600;
long sum = val1 + val2; // Không lỗi, implicit conversion

Ví dụ

using System;
namespace Demo {
    class Program {
        static void Main(string[] args) {
            int val1 = 34567, val2 = 56743;
            long sum = val1 + val2;
            Console.WriteLine("Sum = " + sum);
            Console.ReadLine();
        }
    }
}

Explicit Type Conversion (Ép kiểu tường minh)

Người dùng ép kiểu bằng hàm định nghĩa sẵn.

Ví dụ double -> int:

Ví dụ

using System;
namespace Program {
    class Demo {
        static void Main(string[] args) {
            double d = 1234.89;
            int i = (int)d; // cast
            Console.WriteLine(i);
            Console.ReadKey();
        }
    }
}