溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C#如何實現(xiàn)強制轉(zhuǎn)換

發(fā)布時間:2021-12-01 13:56:29 來源:億速云 閱讀:3606 作者:小新 欄目:編程語言

這篇文章給大家分享的是有關(guān)C#如何實現(xiàn)強制轉(zhuǎn)換的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

int 關(guān)鍵字表示一種整型,是32位的,它的 .NET Framework 類型為 System.Int32。

(int)表示使用顯式強制轉(zhuǎn)換,是一種類型轉(zhuǎn)換。當(dāng)我們從int類型到long、float、double 或decimal 類型,可以使用隱式轉(zhuǎn)換,但是當(dāng)我們從long類型到int類型轉(zhuǎn)換就需要使用顯式強制轉(zhuǎn)換,否則會產(chǎn)生編譯錯誤。

Int32.Parse()表示將數(shù)字的字符串轉(zhuǎn)換為32 位有符號整數(shù),屬于內(nèi)容轉(zhuǎn)換[1]。

我們一種常見的方法:public static int Parse(string)。

如果string為空,則拋出ArgumentNullException 異常;

如果string格式不正確,則拋出FormatException 異常;

如果string的值小于MinValue或大于MaxValue的數(shù)字,則拋出OverflowException異常。

Convert.ToInt32() 則可以將多種類型(包括 object  引用類型)的值轉(zhuǎn)換為 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()三者的應(yīng)用舉幾個例子:   

例子一:

long longType = 100;  int intType  = longType;       // 錯誤,需要使用顯式強制轉(zhuǎn)換  int intType = (int)longType; //正確,使用了顯式強制轉(zhuǎn)換

例子二:

string stringType = "12345";   int intType = (int)stringType;                //錯誤,string 類型不能直接轉(zhuǎn)換為 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 doubleType = Int32.MaxValue + 1.011;   int intType = (int)doubleType;                                //雖然運行正確,但是得出錯誤結(jié)果  int intType = Convert.ToInt32(doubleType)            //拋出 OverflowException 異常

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

***個在對long 類型或是浮點型到int 類型的顯式強制轉(zhuǎn)換中使用,但是如果被轉(zhuǎn)換的數(shù)值大于Int32.MaxValue 或小于 Int32.MinValue,那么則會得到一個錯誤的結(jié)果。

第二個在符合數(shù)字格式的string到int 類型轉(zhuǎn)換過程中使用,并可以對錯誤的string數(shù)字格式的拋出相應(yīng)的異常。

第三個則可以將多種類型的值轉(zhuǎn)換為int類型,也可以對錯誤的數(shù)值拋出相應(yīng)的異常。

無論進行什么類型的數(shù)值轉(zhuǎn)換,數(shù)值的精度問題都是我們必須考慮的。

感謝各位的閱讀!關(guān)于“C#如何實現(xiàn)強制轉(zhuǎn)換”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI