int.Parse() 與 C# 中的 Convert.ToInt32 之間的主要區別是什麼?
使用 C# 中的 int.Parse 或 Convert.ToInt32 方法將數字的字串表示形式轉換為整數。如果字串無法轉換,那麼 int.Parse 或 Convert.ToInt32 方法將返回一個異常
Convert.ToInt32 允許使用 Null 值,它不會引發任何錯誤。Int.parse 不允許使用 Null 值,並且它將引發 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.
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP