is VS as operator

is: return true or false

View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace ConsoleApplication6
 7 {
 8     abstract class Purchasedable
 9     {
10 
11     }
12     abstract class Moveable : Purchasedable
13     {
14 
15     }
16     abstract class Car : Moveable
17     {
18         abstract public void Talk();
19         public void Drive()
20         {
21             Console.WriteLine("WROOOOOOM");
22         }
23         public virtual void TruboBosst()
24         {
25             Console.WriteLine("Styuff and things!");
26         }
27     }
28     class Car1 : Car
29     {
30         public override void Talk()
31         {
32 
33         }
34     }
35     class Program
36     {
37         static void Main(string[] args)
38         {
39             var objects = new List<object>();   //object是所有类型的基类
40             objects.Add(10);
41             objects.Add("Shawn's car");
42             objects.Add(new Car1());
43 
44             foreach (var item in objects)
45             {
46                 if (!(item is Purchasedable)) //Item不是Purchaseable的话就跳出
47                 {
48                     continue;
49                 }
50                 var purchaseable = (Purchasedable)item; //比较as方法
51                 Console.WriteLine("Do you want to purchase item {0}", purchaseable);
52             }
53             Console.ReadLine();
54         }
55     }
56 }

as:可以做的更多,return item type or null

View Code
 1  class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             var objects = new List<object>();   //object是所有类型的基类
 6             objects.Add(10);
 7             objects.Add("Shawn's car");
 8             objects.Add(new Car1());
 9 
10             foreach (var item in objects)
11             {
12                 var purchaseable = item as Purchasedable;//if item is purchaseable return purchaseable type, if not return null
13                 if (purchaseable == null)
14                     continue;
15                 Console.WriteLine("Do you want to purchase item {0}", purchaseable);
16             }
17             Console.ReadLine();
18         }
19     }

注意:is and as不返回reception,不像cast operator

 

posted @ 2013-04-25 11:14  若愚Shawn  阅读(143)  评论(0编辑  收藏  举报