C#數值轉換-顯式數值轉換表(參考)

來源:互聯網
上載者:User

什麼是顯式轉換

Explicit Conversion
就是在將一種類型轉換成另外一種類型時,需要額外的代碼來完成這種轉換。

複製代碼 代碼如下:int n = 1;
byte b = (byte)n; // 正確,顯式轉換
byte b2 = n; // 錯誤

顯式轉換需要注意,它的結果不一定是我們想要的。

複製代碼 代碼如下:int n = 256;
byte b = (byte)n; // 結果是 0

上面的結果是 0,因為超過 255 了,它就從 0 開始;
如果 n 是 257,那麼 b 就是 1;

如果 n 是 258,那麼 b 就是 2;
……

由此還得說下 Convert,Convert 這個類用來轉換類型,它有很多方法,比如 ToInt32,就是轉換成 int。它涉及的類型跨度很大,比如可將 object、string 等轉換成 int,而 (int) 則只能將數字類型轉換成 int。

更多相關內容,請參見 Convert、Parse、TryParse、(int) 的區別。
顯式數值轉換表(摘自 MSDN)

sbyte

byte、ushort、uint、ulong 或 char

byte

Sbyte 或者char

short

sbyte、byte、ushort、uint、ulong 或 char

ushort

sbyte、byte、short 或 char

int

sbyte、byte、short、ushort、uint、ulong 或 char

uint

sbyte、byte、short、ushort、int 或 char

long

sbyte、byte、short、ushort、int、uint、ulong 或 char

ulong

sbyte、byte、short、ushort、int、uint、long 或 char

char

sbyte、byte 或 short

float

sbyte、byte、short、ushort、int、uint、long、ulong、char 或 decimal

double

sbyte、byte、short、ushort、int、uint、long、ulong、char、float 或 decimal

decimal

sbyte、byte、short、ushort、int、uint、long、ulong、char、float 或 double

備忘(摘自 MSDN)

顯式數值轉換可能導致精度損失或引發異常。
將 decimal 值轉換為整型時,該值將舍入為與零最接近的整數值。如果結果整數值超出目標類型的範圍,則會引發 OverflowException。
將 double 或 float 值轉換為整型時,值會被截斷。如果該結果整數值超出了目標值的範圍,其結果將取決於溢出檢查上下文。在 checked 上下文中,將引發 OverflowException;而在 unchecked 上下文中,結果將是一個未指定的目標類型的值。
將 double 轉換為 float 時,double 值將舍入為最接近的 float 值。如果 double 值因過小或過大而使目標類型無法容納它,則結果將為零或無窮大。
將 float 或 double 轉換為 decimal 時,源值將轉換為 decimal 表示形式,並舍入為第 28 個小數位之後最接近的數(如果需要)。根據源值的不同,可能產生以下結果:
如果源值因過小而無法表示為 decimal,那麼結果將為零。
如果源值為 NaN(非數字值)、無窮大或因過大而無法表示為 decimal,則會引發 OverflowException。
將 decimal 轉換為 float 或 double 時,decimal 值將舍入為最接近的 double 或 float 值。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.