Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

C # int.Parse กับ int.TryParse Method


แปลงการแสดงสตริงของตัวเลขเป็นจำนวนเต็มโดยใช้เมธอด int.TryParse และ intParse ใน C#

หากไม่สามารถแปลงสตริงได้ เมธอด int.TryParse จะคืนค่าเท็จ เช่น ค่าบูลีน ในขณะที่ int.Parse จะส่งกลับข้อยกเว้น

ให้เราดูตัวอย่างของวิธีการ int.Parse -

ตัวอย่าง

using System.IO;
using System;
class Program {
   static void Main() {
      int res;
      string myStr = "120";
      res = int.Parse(myStr);
      Console.WriteLine("String is a numeric representation: "+res);
   }
}

ผลลัพธ์

String is a numeric representation: 120

เรามาดูตัวอย่างวิธีการ int.TryParse

ตัวอย่าง

using System.IO;
using System;
class Program {
   static void Main() {
      bool res;
      int a;
      string myStr = "120";
      res = int.TryParse(myStr, out a);
      Console.WriteLine("String is a numeric representation: "+res);
   }
}

ผลลัพธ์

String is a numeric representation: True