zoukankan      html  css  js  c++  java
  • .NET Is 和 As 的区别

    is 和 as 操作符是用来进行强制类型转换的

    is : 检查一个对象是否兼容于其他指定的类型,并返回一个Bool值,永远不会抛出异常

            object o = new object();

            if (o is Label)          {              Label lb = (Label)o;

                 Response.Write("类型转换成功");          }          else          {              Response.Write("类型转换失败");          }

    在上面的代码,CLR实际上会检查两次对象的类型,is操作符先核实一次,如果o兼容于Lable,那么在(Label)o时会再次核实一次,效率比较低,不建议使用

    as:与强制类型转换是一样的,但是永远不会抛出异常,即如果转换不成功,会返回null

            object o = new object();

             Label lb = o as Label;

             if (lb == null)          {              Response.Write("类型转换失败");          }          else          {              Response.Write("类型转换成功");          }

    在上面的代码中,CLR只会进行一次类型核实,效率要高于 is

  • 相关阅读:
    CF763C Timofey and Remoduling
    CF762E Radio Stations
    CF762D Maximum Path
    CF763B Timofey and Rectangles
    URAL1696 Salary for Robots
    uva10884 Persephone
    LA4273 Post Offices
    SCU3037 Painting the Balls
    poj3375 Network Connection
    Golang zip压缩文件读写操作
  • 原文地址:https://www.cnblogs.com/JohnLiang/p/2255390.html
Copyright © 2011-2022 走看看