§ ITPOW >> 文档 >> C#

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

作者:vkvi 来源:ITPOW(原创) 日期:2010-11-14

什么是显式转换

Explicit Conversion

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

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

上面的结果是 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

byteushortuintulong  char

byte

Sbyte 或者char

short

sbytebyteushortuintulong  char

ushort

sbytebyteshort  char

int

sbytebyteshortushortuintulong  char

uint

sbytebyteshortushortint  char

long

sbytebyteshortushortintuintulong  char

ulong

sbytebyteshortushortintuintlong  char

char

sbytebyte  short

float

sbytebyteshortushortintuintlongulongchar  decimal

double

sbytebyteshortushortintuintlongulongcharfloat  decimal

decimal

sbytebyteshortushortintuintlongulongcharfloat  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 值。

相关文章