软件编程
位置:首页>> 软件编程>> C#编程>> C#数值转换-显式数值转换表(参考)

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

  发布时间:2023-05-26 22:26:15 

标签:C#数值转换,显式

什么是显式转换

Explicit Conversion
就是在将一种类型转换成另外一种类型时,需要额外的代码来完成这种转换。


int n = 1;
byte b = (byte)n; // 正确,显式转换
byte b2 = n;      // 错误

显式转换需要注意,它的结果不一定是我们想要的。


int n = 256;
byte b = (byte)n; // 结果是 0



上面的结果是 0,因为超过 255 了,它就从 0 开始;
如果 n 是 257,那么 b 就是 1;

如果 n 是 258,那么 b 就是 2;
……

由此还得说下 Convert,Convert 这个类用来转换类型,它有很多方法,比如 ToInt32,就是转换成 int。它涉及的类型跨度很大,比如可将 object、string 等转换成 int,而 (int) 则只能将数字类型转换成 int。

更多相关内容,请参见 Convert、Parse、TryParse、(int) 的区别。
显式数值转换表(摘自 MSDN)

sbyte

byte、ushort、uint、ulong 或 char

byte

Sbyte 或者char

short

sbyte、byte、ushort、uint、ulong 或 char

ushort

sbyte、byte、short 或 char

int

sbyte、byte、short、ushort、uint、ulong 或 char

uint

sbyte、byte、short、ushort、int 或 char

long

sbyte、byte、short、ushort、int、uint、ulong 或 char

ulong

sbyte、byte、short、ushort、int、uint、long 或 char

char

sbyte、byte 或 short

float

sbyte、byte、short、ushort、int、uint、long、ulong、char 或 decimal

double

sbyte、byte、short、ushort、int、uint、long、ulong、char、float 或 decimal

decimal

sbyte、byte、short、ushort、int、uint、long、ulong、char、float 或 double

备注(摘自 MSDN)

显式数值转换可能导致精度损失或引发异常。
将 decimal 值转换为整型时,该值将舍入为与零最接近的整数值。如果结果整数值超出目标类型的范围,则会引发 OverflowException。
将 double 或 float 值转换为整型时,值会被截断。如果该结果整数值超出了目标值的范围,其结果将取决于溢出检查上下文。在 checked 上下文中,将引发 OverflowException;而在 unchecked 上下文中,结果将是一个未指定的目标类型的值。
将 double 转换为 float 时,double 值将舍入为最接近的 float 值。如果 double 值因过小或过大而使目标类型无法容纳它,则结果将为零或无穷大。
将 float 或 double 转换为 decimal 时,源值将转换为 decimal 表示形式,并舍入为第 28 个小数位之后最接近的数(如果需要)。根据源值的不同,可能产生以下结果:
如果源值因过小而无法表示为 decimal,那么结果将为零。
如果源值为 NaN(非数字值)、无穷大或因过大而无法表示为 decimal,则会引发 OverflowException。
将 decimal 转换为 float 或 double 时,decimal 值将舍入为最接近的 double 或 float 值。

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com