1 (int)
強制轉型為整型。
當将long,float,double,decimal等類型轉換成int類型時可采用這種方式。
double dblNum = 20;
int intDblNum = (int)dblNum;
例子中将double型的dblNum顯式轉換為int型的intDblNum。
2 Convert.ToInt32()
string strNum = "20";
int intStrNum = (int)strNum;
在VS中輸入上面的代碼,會提示:
無法将類型“string”轉換為“int”。
這時,可以使用Convert.ToInt32()方法來完成這個轉換。
int intStrNum = Convert.ToInt32(strNum);
當傳入的字元串(含空串"")無法轉換成int型時,會抛出異常,異常資訊為:
輸入的字元串格式不正确。
string strNotNum = "2x";
int intStrNotNum = Convert.ToInt32(strNotNum);
當傳入參數為null時,Convert.ToInt32()方法會傳回0。
int intStrNotNum = Convert.ToInt16(null);//傳回0,不抛出異常
Convert.ToInt32()方法 可以轉換的類型很多,詳細資訊請參考:
http://msdn.microsoft.com/zh-cn/library/system.convert.aspx
3 Int32.Parse()
Int32.Parse()方法同樣可以将數值型字元串轉換成int。
string strNum = "20";
int intStrNum = int.Parse(strNum);
當傳入的字元串(含空串"")無法轉換成int型時,會抛出異常,異常資訊為:
輸入的字元串格式不正确。
string strNotNum = "2x";
int intStrNotNum = int.Parse(strNotNum);
當傳入參數為null時,會抛出異常,異常資訊為:
參數值不能為null。
int intStrNotNum = int.Parse(null);
4 Int32.TryParse()
Int32.TryParse()方法與Int32.Parse()方法的差別是:如果輸入字元串格式不滿足轉換的要求,Parse方法會抛出異常;而TryParse方法則不會引發異常,它會傳回false表示轉換無法進行,同時會将result置為0。
string strNum = "20";
int intStrNum = 0;
int result = 0;
if (int.TryParse(strNum, out intStrNum))
{
result = intStrNum;
}
string strNotNum = "2x";
int intStrNotNum = 0;
int result = 0;
if (int.TryParse(strNotNum, out intStrNotNum))
{
result = intStrNotNum;
}
當傳入參數為空串””或者null會傳回false。