C#點滴 – 類型轉換

來源:互聯網
上載者:User

1. 寬化轉換() – Widening Conversions

從資料範圍較窄的類型轉換到資料範圍較寬的類型,一般情況下不會帶來資料的損失。

類型

不損失資料的可以轉化目標類型

Byte

UInt16, Int16, UInt32, Int32, UInt64, Int64, Single, Double, Decimal

SByte

Int16, Int32, Int64, Single, Double, Decimal

Int16

Int32, Int64, Single, Double, Decimal

UInt16

UInt32, Int32, UInt64, Int64, Single, Double, Decimal

Char

UInt16, UInt32, Int32, UInt64, Int64, Single, Double, Decimal

Int32

Int64, Double, Decimal

UInt32

Int64, Double, Decimal

Int64

Decimal

UInt64

Decimal

Single

Double

但是在從整形到浮點類型轉換的工程中,可能會造成資料精度損失。

類型

可以轉化目標類型

Int32

Single

UInt32

Single

Int64

Single, Double

UInt64

Single, Double

Decimal

Single, Double

 

2. 窄化轉換 – Narrowing Conversions

基本上.NET是不支援窄化轉換的,所有的隱式的窄化都會造成編譯錯誤。如果真的需要進行窄化轉換,必須要進行強制轉化或者使用System.Convert類中的方法。

 

預設情況下,即使溢出發生,強制窄化不會跑出異常。為了捕捉在窄化轉換髮生的錯誤,經常使用checked關鍵字,如:

        checked {

            int i = 10000;

            short j = (short)i;

        } 

 

而如果使用了System.Convert進行強制窄化轉換,在溢出時一定會拋出異常。下面是一些進行窄化轉換是溢出拋出異常的情況:

類型

轉化的目標類型

Byte

Sbyte

SByte

Byte, UInt16, UInt32, UInt64

Int16

Byte, SByte, UInt16

UInt16

Byte, SByte, Int16

Char

Byte, SByte, Int16, UInt16, UInt32

Int32

Byte, SByte, Int16, UInt16, Int32

UInt32

Byte, SByte, Int16, UInt16, Int32, UInt32, UInt64

Int64

Byte, SByte, Int16, UInt16, Int32, UInt32, Int64

UInt64

Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64

Single

Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64

Double

Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.