Computer >> Máy Tính >  >> Lập trình >> C#

Sự khác biệt chính giữa int.Parse () và Convert.ToInt32 trong C # là gì?

Chuyển đổi biểu diễn chuỗi của số thành số nguyên, sử dụng phương thức int.Parse hoặc Convert.ToInt32 trong C #. Nếu chuỗi không thể được chuyển đổi, thì phương thức int.Parse hoặc Convert.ToInt32 trả về một ngoại lệ

Convert.ToInt32 cho phép giá trị null, nó không tạo ra bất kỳ lỗi nào Int.parse không cho phép giá trị null và nó ném ra lỗi ArgumentNullException.

Ví dụ

Chương trình lớp
class Program {
   static void Main() {
      int res;
      string myStr = "5000";
      res = int.Parse(myStr);
      Console.WriteLine("Converting String is a numeric representation: " + res);
      Console.ReadLine();
   }
}

Đầu ra

Converting String is a numeric representation: 5000

Ví dụ

Chương trình lớp
class Program {
   static void Main() {
      int res;
      string myStr = null;
      res = Convert.ToInt32(myStr);
      Console.WriteLine("Converting String is a numeric representation: " + res);
      Console.ReadLine();
   }
}

Đầu ra

Converting String is a numeric representation: 0

Ví dụ

Chương trình lớp
class Program {
   static void Main() {
      int res;
      string myStr = null;
      res = int.Parse(myStr);
      Console.WriteLine("Converting String is a numeric representation: " + res);
      Console.ReadLine();
   }
}

Đầu ra

Unhandled exception. System.ArgumentNullException: Value cannot be null.