C#中的int.Parse()和Convert.ToInt32之间的主要区别是什么?
使用C#中的int.Parse或Convert.ToInt32方法将数字的字符串表示形式转换为整数。如果无法转换字符串,则int.Parse或Convert.ToInt32方法将返回异常
Convert.ToInt32允许为空值,它不会引发任何错误Int.parse不允许为空值,并且它引发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.
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短