简体   繁体   English

C# 中 is/not/or/and 的优先级

[英]Precedence of is/not/or/and in C#

What is the order of precedence for pattern matching "is not"?模式匹配“不是”的优先顺序是什么? I realized I've written some code like this:我意识到我写了一些这样的代码:

if (x is not TypeA or TypeB)

And implicitly assumed I was writing:并隐含地假设我在写:

if (!(x is TypeA) && !(x is TypeB))

But I just realized that it might be evaluating as:但我刚刚意识到它可能评估为:

if ((!x is TypeA) || (x is TypeB))

In other words, does the "not" apply to an "or separated" list, or does it just apply to the next argument in the list.换句话说,“不”是否适用于“或分隔”列表,还是仅适用于列表中的下一个参数。 Does my original statement need to be written as this instead:我的原始陈述是否需要改为这样写:

if (x is not TypeA and not TypeB)

Here's a test program:这是一个测试程序:

class A { }
class B : A { }
class C : A { }

A a1 = new A();
A a2 = new B();
A a3 = new C();

Console.WriteLine("A is not B or C " + (a1 is not B or C));
Console.WriteLine("B is not B or C " + (a2 is not B or C));
Console.WriteLine("C is not B or C " + (a3 is not B or C));

Console.WriteLine("A is not (B or C) " + (a1 is not (B or C)));
Console.WriteLine("B is not (B or C) " + (a2 is not (B or C)));
Console.WriteLine("C is not (B or C) " + (a3 is not (B or C)));

Console.WriteLine("A is not B and not C " + (a1 is not B and not C));
Console.WriteLine("B is not B and not C " + (a2 is not B and not C));
Console.WriteLine("C is not B and not C " + (a3 is not B and not C));

And here's the output:这是 output:

A is not B or C True
B is not B or C False
C is not B or C True

A is not (B or C) True
B is not (B or C) False
C is not (B or C) False

A is not B and not C True
B is not B and not C False
C is not B and not C False

So "is not (B or C)" is the same as "is not B and not C".所以“不是(B 或 C)”与“不是 B 和不是 C”是一样的。

But "is not B or C" checks that it's not B or is C, which is probably never something you want to do.但是“不是 B 或 C”检查它不是 B 还是 C,这可能永远不是你想做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM