模式匹配“不是”的优先顺序是什么?我意识到我写了一些这样的代码:
if (x is not TypeA or TypeB)
Run Code Online (Sandbox Code Playgroud)
并隐含地假设我正在写:
if (!(x is TypeA) && !(x is TypeB))
Run Code Online (Sandbox Code Playgroud)
但我刚刚意识到它可能被评估为:
if ((!x is TypeA) || (x is TypeB))
Run Code Online (Sandbox Code Playgroud)
换句话说,“不”是否适用于“或分隔”列表,或者仅适用于列表中的下一个参数。我原来的声明是否需要写成这样:
if (x is not TypeA and not TypeB)
Run Code Online (Sandbox Code Playgroud)
Bry*_*ner 13
这是一个测试程序:
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));
Run Code Online (Sandbox Code Playgroud)
这是输出:
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
Run Code Online (Sandbox Code Playgroud)
因此“不是(B 或 C)”与“不是 B 且不是 C”相同。
但“不是 B 或 C”会检查它不是 B 或 C,这可能永远不是您想要做的事情。
| 归档时间: |
|
| 查看次数: |
1118 次 |
| 最近记录: |