C# is 运算符
is 运算符并不是说明对象是某种类型的一种方式,而是可以检查对象是否是给定的类型,或者是否可以转换为给定的类型,如果是,这个运算符就返回true。
is 运算符的语法如下:
<operand> is <type>
这个表达式的结果如下:
- 如果<type>是一个类类型,而<operand>也是该类型,或者它继承了该类型,或者它封箱到该类型中,则结果为true。
- 如果<type>是一个接口类型,而<operand>也是该类型,或者它实现了该接口的类型,则结果为true。
- 如果<type>是一个值类型,而<operand>也是该类型,或者它被拆箱到该类型中,则结果为true。
实例
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MySpace{ class Checker { public void Check(object param1) { if (param1 is ClassA) Console.WriteLine("Variable can be converted to ClassA."); else Console.WriteLine("Variable can't be converted to ClassA."); if (param1 is IMyInterface) Console.WriteLine("Variable can be converted to IMyInterface."); else Console.WriteLine("Variable can't be converted to IMyInterface."); if (param1 is MyStruct) Console.WriteLine("Variable can be converted to MyStruct."); else Console.WriteLine("Variable can't be converted to MyStruct."); } } interface IMyInterface { } class ClassA : IMyInterface { } class ClassB : IMyInterface { } class ClassC { } class ClassD : ClassA { } struct MyStruct : IMyInterface { } class Program { static void Main(string[] args) { Checker check = new Checker(); ClassA try1 = new ClassA(); ClassB try2 = new ClassB(); ClassC try3 = new ClassC(); ClassD try4 = new ClassD(); MyStruct try5 = new MyStruct(); object try6 = try5; Console.WriteLine("Analyzing ClassA type variable:"); check.Check(try1); Console.WriteLine("\nAnalyzing ClassB type variable:"); check.Check(try2); Console.WriteLine("\nAnalyzing ClassC type variable:"); check.Check(try3); Console.WriteLine("\nAnalyzing ClassD type variable:"); check.Check(try4); Console.WriteLine("\nAnalyzing MyStruct type variable:"); check.Check(try5); Console.WriteLine("\nAnalyzing boxed MyStruct type variable:"); check.Check(try6); Console.ReadKey(); } } }
执行结果如下: