给定以下枚举
,
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 theis not
operator added; I findis
/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 ==
,它直接检查实例。这不适用于枚举,但如果您的对象具有用户定义的 ==
运算符且不检查 null
,var != null
很可能会因异常而崩溃,而 var is not null
会如您所愿。
关于c# - 枚举中相等运算符和运算符之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68363850/