当前位置: 移动技术网 > IT编程>开发语言>c# > C#自动类型转换与强制类型转换的讲解

C#自动类型转换与强制类型转换的讲解

2019年07月18日  | 移动技术网IT编程  | 我要评论

自动类型转换

隐式类型转换 - 这些转换是 c# 默认的以安全方式进行的转换, 不会导致数据丢失。例如,从小的整数类型转换为大的整数类型,从派生类转换为基类。

转换规则

从存储范围小的类型到存储范围大的类型。

整数具体规则为:

         byte→short(char)→int→long→float→double

也就是说byte类型的变量可以自动转换为short类型,示例代码:

     byte b = 10;
     short sh = b;

在类型转换时可以跳跃。示例代码:

     byte b1 = 100;            
     int n = b1;

强制类型转换

显式类型转换 - 显式类型转换,即强制类型转换。显式转换需要强制转换运算符,而且强制转换会造成数据丢失。

转换规则

从存储范围大的类型到存储范围小的类型。

具体规则为:

         double→float→long→int→short(char)→byte

例如:

double d = 5673.74;
int i;
i = (int)d;

1.convert.toint32()       2.  int.parse()

convert.toint32() 则可以将多种类型(包括 object  引用类型)的值转换为 int  类型,因为它有许多重载版本:

  •     public static int toint32(object);
  •     public static int toint32(bool);
  •     public static int toint32(byte);
  •     public static int toint32(char);
  •     public static int toint32(decimal);
  •     public static int toint32(double);
  •     public static int toint32(short);
  •     public static int toint32(long);
  •     public static int toint32(sbyte);
  •     public static int toint32(string);

int32.parse()表示将包含数字的字符串转换为32 位有符号整数,属于内容转换

  •     如果 string 为空,则抛出 argumentnullexception 异常;
  •     如果 string 格式不正确,则抛出 formatexception 异常;

可以看出来,convert.toint32() 的功能是最强大的,它把int32.parse()功能包括了,也是说是int32.parse()是convert.toint32() 的一种特殊情况。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。如果你想了解更多相关内容请查看下面相关链接

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网