C# 中“is”操作符的目的是什么?
C# 中的“is”操作符用来检查对象的运行时类型是否与给定类型兼容。
语法如下。
expr is type
其中,expr 是表达式
type 是类型名称
以下是显示 C# 中 is 运算符用法的一个示例。
示例
using System; class One { } class Two { } public class Demo { public static void Test(object obj) { One x; Two y; if (obj is One) { Console.WriteLine("Class One"); x = (One)obj; } else if (obj is Two { Console.WriteLine("Class Two"); y = (Two)obj; } else { Console.WriteLine("None of the classes!"); } } public static void Main() { One o1 = new One(); Two t1 = new Two(); Test(o1); Test(t1); Test("str"); Console.ReadKey(); } }
广告