如何在 C# 中使用 is 运算符?

csharpprogrammingserver side programming更新于 2025/7/13 7:52:17

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

输出

Class One
Class Two
None of the classes!

相关文章