zoukankan      html  css  js  c++  java
  • is和as关键字

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

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

    object o = new object();  
     
    if (o is Label)  
     {  
         Label lb = (Label)o;  
     
         Response.Write("类型转换成功");  
     }  
     else 
     {  
         Response.Write("类型转换失败");  
     } 
    

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

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

    在做项目的时候,我们可以将is和as结合起来使用,由is负责把关检查,as负责转换类型

                foreach (Control item in this.Controls)
                {
                    if (item is Cards)
                    {
                        Cards card = item as Cards;
                    }
                }
    
  • 相关阅读:
    Seven Puzzle Aizu
    Cheese
    Curling 2.0
    Ball
    Property Distribution
    Red and Black
    Lake Counting
    Ants
    剑桥雅思写作高分范文ESSAY20
    剑桥雅思写作高分范文ESSAY19
  • 原文地址:https://www.cnblogs.com/lcxBlog/p/4493170.html
Copyright © 2011-2022 走看看