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 表达家人的祝福语简短