在C#中,咱們能夠看到三種強制類型轉換,好比強制轉換成有符號32位整型,能夠找到下面三種方式:spa
① (int)() ②Convert.ToInt32() ③int.Parse()orm
三種轉變在有些數據時能夠通用,可是用法上仍然有很大的區別ci
(int)表示使用顯式強制轉換,是一種類型轉換。當咱們從 int 類型到 long、float、double 或decimal 類型,能夠使用隱式轉換,可是當咱們從 long 類型到 int 類型轉換就須要使用顯式強制轉換,不然會產生編譯錯誤。字符串
Convert.ToInt32() 則能夠將多種類型(包括 object 引用類型)的值轉換爲 int 類型,由於它有許多重載版本[2]:
public static int ToInt32(object);
public static int ToInt32(bool);
public static int ToInt32(byte);
public static int ToInt32(char);
public static int ToInt32(decimal);
public static int ToInt32(double);
public static int ToInt32(short);
public static int ToInt32(long);
public static int ToInt32(sbyte);
public static int ToInt32(string);string
Int32.Parse()表示將包含數字的字符串轉換爲32 位有符號整數,屬於內容轉換io
咱們一種常見的方法:public static int Parse(string)。
若是 string 爲空,則拋出 ArgumentNullException 異常;
若是 string 格式不正確,則拋出 FormatException 異常;
若是 string 的值小於 MinValue 或大於 MaxValue 的數字,則拋出 OverflowException 異常。
能夠看出來,Convert.ToInt32() 的功能是最強大的,它把Int32.Parse()功能包括了,也是說是Int32.Parse()是Convert.ToInt32() 的一種特殊狀況。編譯