在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() 的一种特殊状况。编译