C#強制轉換:(int)、Int32.Parse() 和 Convert.toInt32()2009-08-18 15:00 zhchongyao cnblogs 我要評論(1)

 http://developer.51cto.com/art/200908/142224.htm

在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]:

  1. public static int ToInt32(object);  
  2.  
  3.  public static int ToInt32(bool);  
  4.  
  5.  public static int ToInt32(byte);  
  6.  
  7.  public static int ToInt32(char);  
  8.  
  9.  public static int ToInt32(decimal);  
  10.  
  11.  public static int ToInt32(double);  
  12.  
  13.  public static int ToInt32(short);  
  14.  
  15.  public static int ToInt32(long);  
  16.  
  17.  public static int ToInt32(sbyte);  
  18.  
  19.  public static int ToInt32(string);  
  20.  
  21.  ......  

(int)和Int32.Parse(),Convert.ToInt32()三者的應用舉幾個例子:   

例子一:

  1. long longType = 100;  
  2. int intType  = longType;       // 錯誤,需要使用顯式強制轉換  
  3. int intType = (int)longType; //正確,使用了顯式強制轉換 

例子二:

  1. string stringType = "12345";   
  2. int intType = (int)stringType;                //錯誤,string 類型不能直接轉換爲 int  類型   
  3. int intType = Int32.Parse(stringType);   //正確 

例子三:

  1. long longType = 100;  
  2. string stringType = "12345";  
  3. object objectType = "54321";  
  4. int intType = Convert.ToInt32(longType);       //正確  
  5. int intType = Convert.ToInt32(stringType);     //正確  
  6. int intType = Convert.ToInt32(objectType);    //正確 

例子四[1]:

  1. double doubleType = Int32.MaxValue + 1.011;   
  2. int intType = (int)doubleType;                                //雖然運行正確,但是得出錯誤結果  
  3. int intType = Convert.ToInt32(doubleType)            //拋出 OverflowException 異常  

C#強制轉換中(int)和Int32.Parse(),Convert.ToInt32()三者的區別:

第一個在對long 類型或是浮點型到int 類型的顯式強制轉換中使用,但是如果被轉換的數值大於Int32.MaxValue 或小於 Int32.MinValue,那麼則會得到一個錯誤的結果。

第二個在符合數字格式的string到int 類型轉換過程中使用,並可以對錯誤的string數字格式的拋出相應的異常。

第三個則可以將多種類型的值轉換爲int類型,也可以對錯誤的數值拋出相應的異常。

無論進行什麼類型的數值轉換,數值的精度問題都是我們必須考慮的。

以上就是C#強制轉換中的相關問題,供大家參考。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章