c# - 枚举中相等运算符和运算符之间的区别

标签 c# enums c#-9.0

给定以下枚举

enum ExampleOptions
{
  OptionA,
  OptionB
}

这两种说法有什么真正的区别吗?

ExampleOptions option = ExampleOptions.OptionA;

bool equals1 = option == ExampleOptions.OptionA; // true
bool equals2 = option is ExampleOptions.OptionA; // true

据我所知,使用 ==is 之间的唯一区别主要是 is 需要一个常量操作数(因此, 操作顺序很重要)。

I used to use the == operator just because I wanted to avoid ugly statements such as
!(option is ExampleOptions.OptionA).
But, after C#9 was released and the is not operator added; I find is/is not a cleaner and more verbose way to write this kind of statements.

决定使用哪个运算符是否有任何隐藏的后果?

最佳答案

As far as I can see, the only difference between using == and is is mainly that is expects a constant operand (thus, operation order matters).

还有很多不同之处,例如 is 允许您编写如下语句:

val is ExampleOptions.OptionA or ExampleOptions.OptionB or ExampleOptions.OptionD

而不是使用 || 并重复命名变量的老式语句。

is 也(这很重要!)不调用 operator ==,它直接检查实例。这不适用于枚举,但如果您的对象具有用户定义的 == 运算符且不检查 nullvar != null 很可能会因异常而崩溃,而 var is not null 会如您所愿。

关于c# - 枚举中相等运算符和运算符之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68363850/

相关文章:

c# - 在 DrawingContext 上绘制时在图像上绘制阴影

c# - 在 VS2019 中测试 C# 9.0 - CS0518 IsExternalInit 未定义或导入......我如何定义/导入它?

c# - 在 C#9 中,仅初始化属性与只读属性有何不同?

强制定义枚举类型的 Java 接口(interface)

我可以用 printf() 显示枚举的值吗?

c++ - 从整数转换为枚举值时如何以及在何处检查错误?

ssl - 如何通过代码将现有的 SSL 证书分配给新的 IIS 站点?

c# - MVC 下拉列表复杂父模型

c# - 查找复制/粘贴代码的工具?

c# - 将 Redis 与 C# : value is not an integer or out of range, sPort : 51410, LastCommand 一起使用时出错: