IS和AS 都是用于类型转换的操作。

但是这两个有什么区别呢?

简单的来说 is 判断成立则返回True,反之返回false。as 成立则返回要转换的对象,不成立则返回Null。

下面掏一手代码来说明一下。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace IsAndAsTest
{
class Program
{
static void Main(string[] args)
{
object child = new Child();
bool b1 = (child is Father);
bool b2 = (child is Mother);
Console.WriteLine(b1);//返回true
Console.WriteLine(b2);//返回false
Console.ReadKey();
}
}
public class Father
{ }
public class Child:Father
{ }
public class Mother
{ }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace IsAndAsTest
{
class Program
{
static void Main(string[] args)
{
object child = new Child();
//bool b1 = (child is Father);
//bool b2 = (child is Mother);
//Console.WriteLine(b1);//返回true
//Console.WriteLine(b2);//返回false
//Console.ReadKey();
Father f1 = child as Father;//可以得到转换成功,得到对象
Mother m1 = child as Mother;//转换失败,m1的值为null
}
}
public class Father
{ }
public class Child:Father
{ }
public class Mother
{ }
}

有一点我要强调一下就是子类可以转换父类,但是父类不能转换为子类,这就比如现在这个社会。你父母的东西是你的,但是你的东西还是你的一样。

            Father F2 = new Father();
Child C1 = (Child)F2;

第二句代码转换的时候就会失败了。因为父类不能强转换为子类。Father不能转换为Child,但是我们如果用As进行转换的话为得到一个null的c1对象。

总结

由他们返回值就可以简单的知道他们的用法。

is 主要用于类型推断,而不需要实际的转换。

as 主要用于真正的类型转换。

最新文章

  1. Jquery判断变量是否为空
  2. Homebrew简介及安装
  3. go sample - format
  4. 跟服务器交互的Web表单(form)
  5. 3.4 C与汇编程序的相互调用
  6. 3种SQL语句分页写法
  7. .NET MVC4 实训记录之六(利用ModelMetadata实现资源的自主访问)
  8. 实践作业2:黑盒测试实践——在被测系统上录制脚本 Day 5
  9. 【JAVA】SWING_ 界面风格
  10. CEF C++调用前端js方法展示传递过来的图片数据
  11. 关于python中loc和iloc方法
  12. BTrace使用简介
  13. ORGANISING THE TEST CASES
  14. 云端搭建内网局域网+NAT冗余上网:vps-centos6.10 +pptp client +2个ros 实现默认走pptp上网,万一pptp断了,走另外一个ros路由+centos7补充了下
  15. Js利用Canvas实现图片压缩
  16. idea ssm项目迁移到另一台机器上时出现不能正常启动项目的解决方案
  17. HDU 3376
  18. 游标 cursor
  19. Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE 解决方法
  20. curl查询公网出口IP

热门文章

  1. DOM LEVEL 1 中的那些事儿[总结篇-上]
  2. Spring IOC 容器源码分析 - 循环依赖的解决办法
  3. CentOS 7 - 创建新用户
  4. Android------------------的快捷键的使用
  5. spring的Java注解方式
  6. Java - 集成开发环境Eclipse的使用方法和技巧
  7. centos 7 Mysql5.7 主从复制配置
  8. C# 多线程七之Parallel
  9. C#基础篇八构造函数和面向对象思想
  10. scala-02-数组的操作