C#点滴 - 类型转换
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 |