標籤:
is運算子的含義:檢查對象是不是給定類型,或者是否可以轉換為給定類型,如果是,這個運算子就返回True.
is運算子的文法:<operand> is <type>
這個運算式的結果如下:如果<type>是一個類類型,而<operand>也是該類型,或者它繼承了該類型,或者它可以封箱到該類型中,則結果返回True.
如果<type>是一個介面類型,而<operand>也是該類型,或者它是實現該介面的類型,則結果返回True.
如果<type>是一個實值型別,而<operand>也是該類型,或者它可以拆箱到該類型中,則返回True.
is執行個體:
1 namespace Chapter11 2 { 3 class Checker 4 { 5 public void Check(object param1) 6 { 7 if (param1 is ClassA) 8 Console.WriteLine("Variable can be converted to ClassA"); 9 else10 Console.WriteLine("Variable can‘t be converted to ClassA.");11 12 if (param1 is IMyInterface)13 Console.WriteLine("Variable can be converted to IMyInterface.");14 else15 Console.WriteLine("Variable can‘t converted to IMyInterface.");16 17 if (param1 is MyStruct)18 Console.WriteLine("Variable can be converted to MyStruct.");19 else20 Console.WriteLine("Variable can‘t be converted to MyStruct.");21 }22 }23 interface IMyInterface24 { }25 class ClassA : IMyInterface26 { }27 class ClassB :IMyInterface28 { }29 30 class ClassC31 { }32 33 class classD : ClassA34 { }35 36 struct MyStruct : IMyInterface37 { }38 class Program39 {40 static void Main(string[] args)41 {42 Checker check = new Checker();43 ClassA try1 = new ClassA();44 ClassB try2 = new ClassB();45 ClassC try3 = new ClassC();46 classD try4 = new classD();47 MyStruct try5 = new MyStruct();48 object try6 = try5;49 Console.WriteLine("Analyzing ClassA type variable:");50 check.Check(try1);51 Console.WriteLine("Analyzing ClassB type variable:");52 check.Check(try2);53 Console.WriteLine("Analyzing ClassC type variable:");54 check.Check(try3);55 Console.WriteLine("Analyzing ClassD type variable:");56 check.Check(try4);57 Console.WriteLine("Analyzing MyStruct type variable:");58 check.Check(try5);59 Console.WriteLine("Analyzing boxed MyStruct type variable:");60 check.Check(try6);61 Console.ReadKey();62 }63 }64 }
C#is運算子的作用