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 |