卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章20156本站已运行346

C# 中的 is 运算符

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

在上面的示例中,检查函数调用语句的类型兼容性。只要被调用的函数是在类型中声明的。结果会是真的。在这种情况下,结果将是错误的。 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 运算符应始终在声明的类型范围内使用。

结论

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

卓越飞翔博客
上一篇: C运算符和标点符号是什么?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏