C# 中"is"运算符的用途是什么?
csharpprogrammingserver side programming更新于 2025/10/12 1:07: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();
}
}

