c# 强制转换(转)C# 2009-10-19 19:01:56 阅读 326 评论 0 字号:大中小 在 C# 中,(int),Int32.Parse() 和 Convert.toInt32() 三种方法有何区别? int 关键字表示一种整型,是32位的,它的 .NET Framework 类型为 System.Int32。 (int)表示使用显式强制转换,是一种类型转换。当我们从 int 类型到 long、float、double 或 decimal 类型,可以使用隐式转换,但是当我们从 long 类型到 int 类型转换就需要使用显式强制转换,否则会产生编译错误。 Int32.Parse()表示将数字的字符串转换为 32 位有符号整数,属于内容转换[1]。 我们一种常见的方法:public static int Parse(string)。 如果 string 为空,则抛出 ArgumentNullException 异常; 如果 string 格式不正确,则抛出 FormatException 异常; 如 果 string 的 值 小 于 MinValue 或 大 于 MaxValue 的 数 字 , 则 抛 出 OverflowException 异常。 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); ...... (int)和 Int32.Parse(),Convert.ToInt32()三者的应用举几个例子: 例子一: long longType = 100; int intType = longType; // 错误,需要使用显式强制转换 int intType = (int)longType; //正确,使用了显式强制转换 例子二: string stringType = "12345"; int intType = (int)stringType; //错误,string 类型不能直接转换为 int 类型 int intType = Int32.Parse(stringType); //正确 例子三: long longType = 100; string stringType = "12345"; object objectType = "54321"; int intType = Convert.ToInt32(longType); //正确 int intType = Convert.ToInt32(stringType); //正确 int intType = Convert.ToInt32(objectType); //正确 例子四[1]: double dou...