將字串轉換為整數
有多種方法可用於將 string
顯式轉換為 integer
,例如:
-
Convert.ToInt16();
-
Convert.ToInt32();
-
Convert.ToInt64();
-
int.Parse();
但是如果輸入字串包含非數字字元,則所有這些方法都將丟擲 FormatException
。為此,我們需要編寫一個額外的異常處理(try..catch
)來處理這種情況。
示例說明:
那麼,讓我們的輸入是:
string inputString = "10.2";
例 1: Convert.ToInt32()
int convertedInt = Convert.ToInt32(inputString); // Failed to Convert
// Throws an Exception "Input string was not in a correct format."
注意: 其他提到的方法也是如此 - Convert.ToInt16();
和 Convert.ToInt64();
例 2: int.Parse()
int convertedInt = int.Parse(inputString); // Same result "Input string was not in a correct format.
我們如何規避這個?
如前所述,為了處理異常,我們通常需要一個 try..catch
,如下所示:
try
{
string inputString = "10.2";
int convertedInt = int.Parse(inputString);
}
catch (Exception Ex)
{
//Display some message, that the conversion has failed.
}
但是,在任何地方使用 try..catch
都不是一個好習慣,如果輸入錯誤,我們可能會在某些情況下給出 0
*(如果我們按照上面的方法,我們需要從 catch 塊中分配 0
到 convertedInt
)。*為了處理這種情況,我們可以使用一種名為 .TryParse()
的特殊方法。
.TryParse()
方法具有內部異常處理,它將為 out
引數提供輸出,並返回指示轉換狀態的布林值 (如果轉換成功則返回 *true
;如果失敗則返回 false
)。*根據返回值,我們可以確定轉換狀態。讓我們看一個例子:
用法 1: 將返回值儲存在布林變數中
int convertedInt; // Be the required integer
bool isSuccessConversion = int.TryParse(inputString, out convertedInt);
我們可以在執行後檢查變數 isSuccessConversion
來檢查轉換狀態。如果它是假的話,那麼 convertedInt
的值將是 0
(如果你想要 0
用於轉換失敗,則無需檢查返回值)。
用法 2: 用 if
檢查返回值
if (int.TryParse(inputString, out convertedInt))
{
// convertedInt will have the converted value
// Proceed with that
}
else
{
// Display an error message
}
用法 3: 不檢查返回值你可以使用以下,如果你不關心返回值 (轉換與否,0
就可以了)
int.TryParse(inputString, out convertedInt);
// use the value of convertedInt
// But it will be 0 if not converted