C# 提供一组 整数 和 浮点 数值类型。 任何两种数值类型(隐式或显式)之间存在转换。 必须使用 强制转换表达式 来执行显式转换。
隐式数值转换
下表显示了内置数值类型之间的预定义隐式转换:
来自 | 到 |
---|---|
sbyte |
short 、、int 、float long 、double 、、decimal 或nint |
byte |
short 、、ushort 、uint int 、、ulong long 、float 、、double 、decimal 或 nint nuint |
短 |
int 、、long 、double float 、或decimal 或nint |
ushort |
int 、、uint 、long 、ulong 、float 、double 或decimal 、或 nint nuint |
int |
long 、、float double 、或decimal nint |
uint |
long 、、ulong 、double float 、或decimal 或nuint |
长 |
float 、double 或 decimal |
ulong |
float 、double 或 decimal |
漂浮 | double |
nint |
long 、float 、double 或 decimal |
nuint |
ulong 、float 、double 或 decimal |
注释
隐式转换从int
、、uint
、long
ulong
nint
或nuint
与long
float
、ulong
或nint
,或nuint
double
可能导致精度损失,但永远不会丢失数量级。 其他隐式数值转换不会丢失任何信息。
另请注意,
没有对和
sbyte
类型的隐式转换byte
。 没有来自double
和decimal
类型的隐式转换。类型与
float
类型double
之间decimal
没有隐式转换。类型的
int
常量表达式的值(例如,由整数文本表示的值)可以隐式转换为sbyte
、byte
、、short
、ushort
、uint
ulong
、、nint
或nuint
目标类型范围内的值:byte a = 13; byte b = 300; // CS0031: Constant value '300' cannot be converted to a 'byte'
如前面的示例所示,如果常量值不在目标类型范围内,则会发生编译器错误 CS0031 。
显式数值转换
下表显示了没有 隐式转换的内置数值类型之间的预定义显式转换:
来自 | 到 |
---|---|
sbyte |
byte 、ushort 、uint 、ulong 或 nuint |
byte | sbyte |
短 |
sbyte 、 byte 、 ushort 、 uint 、 ulong 或 nuint |
ushort |
sbyte 、byte 或 short |
int |
sbyte 、、byte 、ushort short 、uint 、、ulong 或nuint |
uint |
sbyte 、 byte 、 short 、 ushort 、 int 或 nint |
长 |
sbyte 、、byte 、ushort short 、int 、uint 、ulong 、或 nint nuint |
ulong |
sbyte 、、byte 、ushort short 、int 、uint 、long 、或 nint nuint |
漂浮 |
sbyte 、、byte 、ushort short 、、uint int 、long 、、ulong 、decimal 或 nint nuint |
双 |
sbyte 、byte 、、ushort short 、int 、uint 、long 、ulong 、、float 、decimal 或 nint nuint |
十进制 |
sbyte 、byte 、、ushort short 、int 、uint 、long 、ulong 、、float 、double 或 nint nuint |
nint |
sbyte 、、byte 、ushort short 、int 、uint 、、 ulong 或nuint |
nuint |
sbyte 、、byte 、ushort short 、int 、uint 、、 long 或nint |
注释
显式数值转换可能会导致数据丢失或引发异常,通常是一个 OverflowException。
另请注意:
将整型类型的值转换为另一个整型类型时,结果取决于 溢出检查上下文。 在选中的上下文中,如果源值在目标类型范围内,转换会成功。 否则会引发 OverflowException。 在不受限制的上下文中,转换总是成功的,具体过程如下:
如果源类型大于目标类型,则通过放弃其“额外”最重要的位来截断源值。 结果会被视为目标类型的值。
如果源类型小于目标类型,则源值为符号扩展或零扩展,使其大小与目标类型相同。 如果源类型已签名,则使用签名扩展;如果源类型未签名,则使用零扩展。 结果会被视为目标类型的值。
如果源类型的大小与目标类型相同,则源值被视为目标类型的值。
将值转换为
decimal
整型时,此值将舍入为零到最接近的整数值。 如果生成的整型值超出目标类型的范围,则会引发一个 OverflowException 。将某个
double
或float
值转换为整型时,此值将舍入为零到最接近的整型值。 如果生成的整型值超出目标类型的范围,则结果取决于 溢出检查上下文。 在已检查的上下文中,将引发一个 OverflowException ,而在未选中的上下文中,结果是目标类型的未指定值。转换为
double
float
时,该值double
将舍入为最接近float
的值。double
如果值太小或太大而无法容纳到float
类型中,则结果为零或无穷大。转换
float
或double
转换为decimal
时,源值将转换为decimal
表示形式,并在第 28 位小数后舍入为最接近的数字(如有必要)。 根据源值的值,可能会出现以下结果之一:如果源值太小,无法表示为 a
decimal
,则结果为零。如果源值为 NaN(不是数字)、无穷大或太大,无法表示为 a
decimal
,则会引发一个 OverflowException 。
转换为或
double
转换decimal
float
时,源值将分别舍入到最接近float
的值或double
值。
C# 语言规范
有关更多信息,请参阅 C# 语言规范的以下部分: