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.
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP