使用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.