C#中的强制类型转换与as转换的区别

 

C#中的强制类型转换

例如有ClassA与ClassB两个类
创建两个类的对象进行转换

1
2
ClassA a = new ClassA();
  ClassB b = new ClassB();

如果使用强制转换

1
ClassB c = (ClassB)a;

会报InvalidCastException异常 无法将类型为ClassA的对象强制转换为类型ClassB

若使用as关键字进行转换则

1
2
3
4
5
ClassB c=a as ClassB;
  if (c!= null )
  {
  MessageBox.Show(c.ToString());
  }

如果a和ClassB不兼容,则返回null给c

 

在C#中,我们可以看到三种强制类型转换,比如强制转换成有符号32位整型,可以找到下面三种方式:

① (int)()                ②Convert.ToInt32()         ③int.Parse()

 

三种转变在有些数据时可以通用,但是用法上仍然有很大的区别

(int)表示使用显式强制转换,是一种类型转换。当我们从 int 类型到 long、float、double 或decimal 类型,可以使用隐式转换,但是当我们从 long 类型到 int  类型转换就需要使用显式强制转换,否则会产生编译错误。

Convert.ToInt32() 则可以将多种类型(包括 object  引用类型)的值转换为 int  类型,因为它有许多重载版本[2]:
    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 位有符号整数,属于内容转换

    我们一种常见的方法:public static int Parse(string)。
    如果 string 为空,则抛出 ArgumentNullException 异常;
    如果 string 格式不正确,则抛出 FormatException 异常;
    如果 string 的值小于 MinValue 或大于 MaxValue 的数字,则抛出 OverflowException 异常。
 可以看出来,Convert.ToInt32() 的功能是最强大的,它把Int32.Parse()功能包括了,也是说是Int32.Parse()Convert.ToInt32() 的一种特殊情况。

转载于:https://www.cnblogs.com/chengjun/p/5336856.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值