C# 中的 Is 运算符


Is 运算符也称为类型兼容性运算符,在 C# 结构中起着不可或缺的作用。让我们尝试理解这个运算符。

C# 的 Is 运算符检查给定对象是否与另一个对象兼容,如果兼容则返回 true,否则返回 false。

语法

expression is obj

示例

Expression 是您想要检查与之兼容性的对象。表达式可以包含变量、文字和方法调用。Obj 是验证表达式所针对的类型。这可以包括内置类型和用户定义类型。

// The operation of the type compatibility operator is performed. Console.Writeline("Happy Holidays" is string); Console.Writeline(42 is string);

输出

True
False

让我们理解这个输出。我们知道“Happy Holidays”是一个字符串文字,42 是一个整数。“Happy Holidays”与字符串数据类型进行检查时,结果为 true,因为它兼容。当 42 与字符串进行检查时,结果为 false,因为它不兼容。

表达式

字面量表达式

字面量表达式由数字、字符序列(字符串)、数组等组成。

示例

// The operation of the type compatibility operator is performed. Console.Writeline("Happy Holidays" is string);

输出

TRUE

变量表达式

变量表达式将包含充当容器的对象,这些对象保存值或引用。

示例

// an object is declared with string data type. object str= "Happy Holidays"; // The operation of the type compatibility operator is performed. Console.Writeline(str is string);

输出

TRUE

函数调用表达式

函数调用表达式将在 is 运算符的左侧具有函数调用。

示例

// A class declaration class class_dec{} // an object is declared. object str= Method_in_the_class(); // The operation of the type compatibility operator is performed. Console.Writeline(str is class_dec);

输出

TRUE

在上面的示例中,检查函数调用语句的类型兼容性。只要调用的函数在类型中声明,结果都将为 true。在本例中,结果将为 false。class_dec 是一个空类。

类型

内置类型

C# 中的预定义类型可以在 is 运算符的右侧使用。它可以是整数、字符、浮点数和布尔值。

示例

// an object is declared with numeric data type. object num= 42; // The operation of the type compatibility operator is performed. Console.Writeline(num is int);

输出

TRUE

用户定义类型

is 运算符也可以检查用户定义的类型。它包括类、枚举等。

示例

// A class declaration class class_dec{} // an instance of the class is declared. class_dec str= new class_dec(); // The operation of the type compatibility operator is performed. Console.Writeline(str is class_dec);

输出

TRUE

在上面的示例中,is 运算符将对象与用户定义的数据类型进行比较。

注意 - is 运算符也可以与 NULL 一起使用。如果表达式不为 null,则运算符将始终返回 false 作为输出。

用户定义类型的范围会影响输出。is 运算符应始终在声明类型的范围内使用。

Learn C# in-depth with real-world projects through our C# certification course. Enroll and become a certified expert to boost your career.

结论

在本文中,我们重点介绍了 C# 中的 is 运算符。我们分析了语法并了解了 is 运算符可以使用的各种情况。is 运算符的使用通过各种代码片段和示例进行了说明。

更新于:2023年4月25日

307 次查看

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告