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();
   }
}

更新日期: 2020 年 6 月 23 日

183 次浏览

开启你的职业生涯

完成课程即可获得认证

开始学习
广告