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 婆婆高寿祝福语大全简短