Item 3: Prefer the is or as Operators to Casts(Effective C#)

  Remember that user-defined conversion operators operate only on the compile-time type of an object, not on the runtime type.
  Now that you know to use as when possible, let’s discuss when you can’t use it. The as operator does not work on value types. 
  The is operator should be used only when you cannot convert the type using as. Otherwise, it’s simply redundant.
  foreach uses a cast operation to perform conversions from an object to the type used in the loop. foreach needs to use casts to support both value types and reference types. By choosing the cast operator, the foreach statement exhibits the same behavior, no matter what the destination type is. However, because a cast is used, foreach loops can cause an InvalidCastException to be thrown.
 1  using  System;
 2  using  System.Collections.Generic;
 3  using  System.Linq;
 4  using  System.Text;
 5  using  System.Collections;
 6 
 7  namespace  EffectiveCSharpItem3
 8  {
 9       public   class  MyType 
10      {
11      }
12 
13       public   class  SecondType 
14      {
15           private  MyType type  =   new  MyType();
16 
17           public   static   implicit   operator  MyType(SecondType t)
18          {
19               return  t.type;
20          }
21      }
22 
23       class  Program
24      {
25           static   void  Main( string [] args)
26          {
27              SecondType st  =   new  SecondType();
28              MyType t  =  (MyType)st;
29 
30              IEnumerable collection  =   new  List < int > () {  1 2 3 4 5 6 7 8 9 10  };
31              var small  =  from  int  item  in  collection
32                           where  item  <   5
33                          select item;
34              var small2  =  collection.Cast < int > ().Where(item  =>  item  <   5 );
35               foreach  ( int  i  in  small) 
36              {
37                  Console.WriteLine(i);
38              }
39 
40               foreach  ( int  i  in  small2)
41              {
42                  Console.WriteLine(i);
43              }
44              Console.WriteLine(t  ==   null );
45              Console.Read();
46          }
47      }
48  }

 

 

转载于:https://www.cnblogs.com/zhtf2014/archive/2011/01/09/1931102.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值