C#强制转换中(int)和Int32.Parse(),Convert.ToInt32()三者的区别

C#强制转换中(int)和Int32.Parse(),Convert.ToInt32()三者的区别: 

第一个在对long 类型或是浮点型到int 类型的显式强制转换中使用,但是如果被转换的数值大于Int32.MaxValue 或小于 Int32.MinValue,那么则会得到一个错误的结果。 

第二个在符合数字格式的string到int 类型转换过程中使用,并可以对错误的string数字格式的抛出相应的异常。

第三个则可以将多种类型的值转换为int类型,也可以对错误的数值抛出相应的异常。 

无论进行什么类型的数值转换,数值的精度问题都是我们必须考虑的。

 

(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);    //正确 

    例子四:

double doubleType = Int32.MaxValue + 1.011;   

int intType = (int)doubleType;                       //虽然运行正确,但是得出错误结果  

int intType = Convert.ToInt32(doubleType)            //抛出 OverflowException 异常 

posted @ 2012-05-04 11:24  刘增双_2010  阅读(214)  评论(0编辑  收藏  举报