ylbtech-Docs-.NET-C#-指南-语言参考-关键字-值类型:内置数值转换 |
1.返回顶部 |
1、
内置数值转换(C# 参考)
- 2019/10/22
C# 提供了一组整型和浮点数值类型。 任何两种数值类型之间都可以进行隐式或显式转换。 必须使用强制转换运算符 ()
才能调用显式转换。
隐式数值转换
下表显示内置数值类型之间的预定义隐式转换:
From | 到 |
---|---|
sbyte | short 、int 、long 、float 、double 或 decimal |
byte | short 、ushort 、int 、uint 、long 、ulong 、float 、double 或 decimal |
short | int 、long 、float 、double 或 decimal |
ushort | int 、uint 、long 、ulong 、float 、double 或 decimal 。 |
int | long 、float 、double 或 decimal |
uint | long 、ulong 、float 、double 或 decimal |
long | float 、double 或 decimal |
ulong | float 、double 或 decimal |
float | double |
备注
从 int
、uint``long
或 ulong
到 float
的隐式转换以及从 long
或 ulong
到 double
的隐式转换可能会丢失精准率,但绝不会丢失一个数量级。 其他隐式数值转换不会丢失任何信息。
另请注意
- 任何整型数值类型都可以隐式转换为任何浮点数值类型。
- 不存在针对
byte
和sbyte
类型的隐式转换。 不存在从double
和decimal
类型的隐式转换。 decimal
类型和float
或double
类型之间不存在隐式转换。- 类型
int
的常量表达式的值(例如,由整数文本所表示的值)如果在目标类型的范围内,则可隐式转换为sbyte
、byte
、short
、ushort
、uint
或ulong
:C#复制
byte a = 13; byte b = 300; // CS0031: Constant value ‘300‘ cannot be converted to a ‘byte‘
如前面的示例所示,如果该常量值不在目标类型的范围内,则发生编译器错误 CS0031。
显式数值转换
下表显示不存在隐式转换的内置数值类型之间的预定义显式转换:
From | 到 |
---|---|
sbyte | byte 、ushort 、uint 或 ulong |
byte | sbyte |
short | sbyte 、byte 、ushort 、uint 或 ulong |
ushort | sbyte 、byte 或 short |
int | sbyte 、byte 、short 、ushort 、uint 或 ulong |
uint | sbyte 、byte 、short 、ushort 或 int |
long | sbyte 、byte 、short 、ushort 、int 、uint 或 ulong 。 |
ulong | sbyte 、byte 、short 、ushort 、int 、uint 或 long 。 |
float | sbyte 、byte 、short 、ushort 、int 、uint 、long 、ulong 或 decimal |
double | sbyte 、byte 、short 、ushort 、int 、uint 、long 、ulong 、float 或 decimal |
decimal | sbyte 、byte 、short 、ushort 、int 、uint 、long 、ulong 、float 或 double |
备注
显式数值转换可能会导致数据丢失或引发异常,通常为 OverflowException。
另请注意
- 将整数类型的值转换为另一个整数类型时,结果取决于溢出检查上下文。 在已检查的上下文中,如果源值在目标类型的范围内,则转换成功。 否则会引发 OverflowException。 在未检查的上下文中,转换始终成功,并按如下方式进行:
- 如果源类型大于目标类型,则通过放弃其“额外”最高有效位来截断源值。 结果会被视为目标类型的值。
- 如果源类型小于目标类型,则源值是符号扩展或零扩展,以使其与目标类型的大小相同。 如果源类型带符号,则是符号扩展;如果源类型是无符号的,则是零扩展。 结果会被视为目标类型的值。
- 如果源类型与目标类型的大小相同,则源值将被视为目标类型的值。
- 将
decimal
值转换为整型类型时,此值会向零舍入到最接近的整数值。 如果生成的整数值处于目标类型的范围之外,则会引发 OverflowException。 - 将
double
或float
值转换为整型类型时,此值会向零舍入到最接近的整数值。 如果生成的整数值处于目标类型范围之外,则结果会取决于溢出上下文。 在已检查的上下文中,引发 OverflowException;而在未检查的上下文中,结果是目标类型的未指定值。 - 将
double
转换为float
时,double
值舍入为最接近的float
值。 如果double
值太小或太大,无法匹配float
类型,结果将为零或无穷大。 - 将
float
或double
转换为decimal
时,源值转换为decimal
表示形式,并并五入到第 28 位小数后最接近的数(如果需要)。 根据源值的值,可能出现以下结果之一:- 如果源值太小,无法表示为
decimal
,结果则为零。 - 如果源值为 NaN(非数值)、无穷大或太大而无法表示为
decimal
,则引发 OverflowException。
- 如果源值太小,无法表示为
- 将
decimal
转换为float
或double
时,源值分别舍入为最接近的float
或double
值。
C# 语言规范
有关更多信息,请参阅 C# 语言规范的以下部分:
请参阅
2、
2.返回顶部 |
3.返回顶部 |
4.返回顶部 |
5.返回顶部 |
1、
https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/builtin-types/numeric-conversions
2、
6.返回顶部 |
作者:ylbtech 出处:http://ylbtech.cnblogs.com/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 |
原文地址:https://www.cnblogs.com/storebook/p/11846193.html
时间: 2024-12-21 00:42:46