天天看點

在 C# 中,(int) ,Int32.Parse() 和 Convert.toInt32() 三種方法的差別

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

    例子三:

    string stringType = "12345";

    object objectType = "54321";

    int intType = Convert.ToInt32(longType);       //正确

    int intType = Convert.ToInt32(stringType);     //正确

    int intType = Convert.ToInt32(objectType);    //正确

    例子四[1]:

    double doubleType = Int32.MaxValue + 1.011; 

    int intType = (int)doubleType;                                //雖然運作正确,但是得出錯誤結果

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

   (int)和Int32.Parse(),Convert.ToInt32()三者的差別:

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

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

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

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

    本文引用:

    [2] CSDN 

原文:http://blog.csdn.net/scucj/article/details/846344