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 生日广州男生祝福语简短