如何在 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();
}
}输出
Class One Class Two None of the classes!
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP