is和as初步

来源:互联网 发布:京北方兼职数据录入 编辑:程序博客网 时间:2024/05/16 18:58

is as 都是类型之间的转换

不同点:

is 如果转换成功,则返回一个true,否则返回一个false

as如果转换成功则返回对应的对象,否则返回一个null

is的用法:

            Person p =new Student("student", 18,'M',310);

            if (pis Student)      //如果per能转成Student类型,则返回true,否则返回false

           {

               ((Student)p).StudentSay();

           }

           else

           {

               Console.WriteLine("无法完成对应的转换");

           }

输出:


如果是:

          Person p =new Student("student", 18,'M',310);

          if (pis Teacher) //如果per能转成Student类型,则返回true,否则返回false

           {

               ((Teacher)p).TeacherSay();

           }

           else

           {

               Console.WriteLine("无法完成对应的转换?");

           }

输出:


as的用法:

            Person p =new Student("student", 18,'M',310);

           Student s= pas Student;

调试结束后如下图发现:


发现有了ID,说明转换成功

如果换成了:

            Person p =new Student("student", 18,'M',310);

           Teacher s= p as Teacher;

则:发现下图返回了null空


小结:

as转换成功则返回相应的对象,转换失败会返回null,而不会报异常

 

使用is进行转换,成功了返回true,失败了返回false,不会报异常。

 

但是强制类型转换如果成功了,则返回对应的对象,如果失败了则报异常。


0 0