显式数值转换表(C# 参考)

显式数值转换用于通过显式转换表达式,将任何数字类型转换为任何其他数字类型。对于它不存在隐式转换。下表显示了这些转换。

有关转换的更多信息,请参见 强制转换和类型转换(C# 编程指南)

目标
sbyte byteushortuintulongchar
byte Sbytechar
short sbytebyteushortuintulongchar
ushort sbytebyteshortchar
int sbytebyteshortushortuintulongchar
uint sbytebyteshortushortintchar
long sbytebyteshortushortintuintulongchar
ulong sbytebyteshortushortintuintlongchar
char sbytebyteshort
float sbytebyteshortushortintuintlongulongchardecimal
double sbytebyteshortushortintuintlongulongcharfloatdecimal
decimal sbytebyteshortushortintuintlongulongcharfloatdouble

备注

  • 显式数值转换可能导致精度损失或引发异常。

  • decimal 值转换为整型时,该值将舍入为与零最接近的整数值。如果结果整数值超出目标类型的范围,则会引发 OverflowException

  • doublefloat 值转换为整型时,值会被截断。如果该结果整数值超出了目标值的范围,其结果将取决于溢出检查上下文。在 checked 上下文中,将引发 OverflowException;而在 unchecked 上下文中,结果将是一个未指定的目标类型的值。

  • double 转换为 float 时,double 值将舍入为最接近的 float 值。如果 double 值因过小或过大而使目标类型无法容纳它,则结果将为零或无穷大。

  • floatdouble 转换为 decimal 时,源值将转换为 decimal 表示形式,并舍入为第 28 个小数位之后最接近的数(如果需要)。根据源值的不同,可能产生以下结果:

    • 如果源值因过小而无法表示为 decimal,那么结果将为零。

    • 如果源值为 NaN(非数字值)、无穷大或因过大而无法表示为 decimal,则会引发 OverflowException

  • decimal 转换为 floatdouble 时,decimal 值将舍入为最接近的 doublefloat 值。

有关显式转换的更多信息,请参见“C# 语言规范中的显式”。有关如何访问此规范的更多信息,请参见 C# 语言规范

请参阅

C# 参考

C# 编程指南

强制转换和类型转换(C# 编程指南)

() 运算符(C# 参考)

整型表(C# 参考)

内置类型表(C# 参考)

隐式数值转换表(C# 参考)