为什么运算符的行为类似于==运算符? [英] Why does is operator behave like == operator?

查看:69
本文介绍了为什么运算符的行为类似于==运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有这样的声明:

Assume we have statement like this:

enum EngineType
{
   Gasoline,
   Diesel,
   Electric
}

var engine = EngineType.Electric;

if (engine is EngineType.Electric)
{
    // do something
}

为什么if语句为true.从Microsoft文档中: is运算符检查表达式的结果是否与给定类型兼容.

Why does if statement is true. From microsoft documentation: The is operator checks if the result of an expression is compatible with a given type.

EngineType(枚举)的左值类型和整数的右值类型不是吗?我想念什么吗?

Isn't the left value type of EngineType (enum) and right value type of integer? Am I missing something?

推荐答案

因为使用

Because when you use the is keyword this way, you are actually doing Pattern Matching (starting with C# 7.0) :

恒定模式,用于测试表达式是否计算为指定的常数值.

Constant pattern, which tests whether an expression evaluates to a specified constant value.

这篇关于为什么运算符的行为类似于==运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆