C#中的as运算符

as   运算符用于执行可兼容类型之间的转换。as   运算符用在以下形式的表达式中:  
   
  expression   as   type  
  此处:    
   
  expression    
  引用类型的表达式。    
  type    
  引用类型。    
  备注  
  as   运算符类似于类型转换,所不同的是,当转换失败时,as   运算符将产生空,而不是引发异常。在形式上,这种形式的表达式:  
   
  expression   as   type  
  等效于:  
   
  expression   is   type   ?   (type)expression   :   (type)null  
  只是   expression   只被计算一次。  
   
  示例  
  //   cs_keyword_as.cs  
  //   The   as   operator  
  using   System;  
  class   MyClass1    
  {  
  }  
   
  class   MyClass2    
  {  
  }  
   
  public   class   IsTest    
  {  
        public   static   void   Main()    
        {  
              object   []   myObjects   =   new   object[6];  
              myObjects[0]   =   new   MyClass1();  
              myObjects[1]   =   new   MyClass2();  
              myObjects[2]   =   "hello";  
              myObjects[3]   =   123;  
              myObjects[4]   =   123.4;  
              myObjects[5]   =   null;  
   
              for   (int   i=0;   i<myObjects.Length;   ++i)    
              {  
                    string   s   =   myObjects[i]   as   string;  
                    Console.Write   ("{0}:",   i);  
                    if   (s   !=   null)  
                          Console.WriteLine   (   "'"   +   s   +   "'"   );  
                    else  
                          Console.WriteLine   (   "not   a   string"   );  
              }  
        }  
  }  
  输出  
  0:not   a   string  
  1:not   a   string  
  2:'hello'  
  3:not   a   string  
  4:not   a   string  
  5:not   a   string   
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值