int.Parse() 與 C# 中的 Convert.ToInt32 之間的主要區別是什麼?


使用 C# 中的 int.Parse 或 Convert.ToInt32 方法將數字的字串表示形式轉換為整數。如果字串無法轉換,那麼 int.Parse 或 Convert.ToInt32 方法將返回一個異常

Convert.ToInt32 允許使用 Null 值,它不會引發任何錯誤。Int.parse 不允許使用 Null 值,並且它將引發 ArgumentNullException 錯誤。

示例

 即時演示

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();
   }
}

輸出

Converting String is a numeric representation: 5000

示例

 即時演示

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();
   }
}

輸出

Converting String is a numeric representation: 0

示例

 即時演示

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();
   }
}

輸出

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

更新於:08-Aug-2020

5,000+ 次瀏覽

開啟你的 職業

透過完成課程獲取認證

開始
廣告
© . All rights reserved.