[英]Precedence of is/not/or/and in C#
模式匹配“不是”的优先顺序是什么? 我意识到我写了一些这样的代码:
if (x is not TypeA or TypeB)
并隐含地假设我在写:
if (!(x is TypeA) && !(x is TypeB))
但我刚刚意识到它可能评估为:
if ((!x is TypeA) || (x is TypeB))
换句话说,“不”是否适用于“或分隔”列表,还是仅适用于列表中的下一个参数。 我的原始陈述是否需要改为这样写:
if (x is not TypeA and not TypeB)
这是一个测试程序:
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));
这是 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
所以“不是(B 或 C)”与“不是 B 和不是 C”是一样的。
但是“不是 B 或 C”检查它不是 B 还是 C,这可能永远不是你想做的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.