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.