简体   繁体   中英

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:

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".

But "is not B or C" checks that it's not B or is C, which is probably never something you want to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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