使用 "is not" 运算符检查 2 个变量是否不是同一类型在 C# 中不起作用

Checking if 2 variables are not the same type using the "is not" operator doesn't work in C#

所以我想知道一个变量是否不是 BuiltInClass 类型。 这个 BuiltInClass 类型只是我用 C# 编写的 class。 在 Whosebug 搜索后,我看到使用“是”和“不是”运算符我可以测试变量是否是某种类型。 现在,我尝试了这个并且它正在工作,但出于某种原因,如果我将该条件放在 if 语句中它不起作用。

这是我检查类型的代码。我在评论中留下了一些额外的信息。

Console.WriteLine(value.GetType()); //Prints Acrylian.BuiltInClass
Console.WriteLine($"value is BuiltInClass == {value is BuiltInClass}"); //Prints "value is BuiltInClass == True"

if (value is not BuiltInClass || value is not ClassValue) // "is not" operator so should return false
{                                                           //but this code is still run
    Console.WriteLine("Setting context");
    value.SetContext(context);
}

这是我的“值”变量定义:

dynamic? value = context.symbolTable.Get(varName);

我只是不明白为什么在代码片段的第 1 行和第 2 行它清楚地说它们是同一类型,但 if 语句中的代码仍然得到 运行.

澄清一下:我知道我使用的是“不是”运算符,但是当它们是同一类型时,这应该使代码不 运行 对吗?

此致

感谢评论部分,我找到了解决方案。 所以我改变了if (value is not BuiltInClass || value is not ClassValue)if (!(value is BuiltInClass || value is ClassValue)),现在可以使用了。

您误解了布尔表达式。

假设 value 的类型是 BuiltInClass:

然后

  • value is not BuiltInClass 将为假。
  • value is not ClassValue 为真。

因此

value is not BuiltInClass || value is not ClassValue

解析为

false || true => true

您通过使用 if (!(value is BuiltInClass || value is ClassValue)) 来“修复”了这个问题,但这并不等同于您的原始代码!

这相当于:

if (value is not BuiltInClass && value is not ClassValue) 

注意使用 && 而不是 ||

有关布尔转换的详细信息,请参阅 De Morgan's laws

特别注意变换:

not (A or B) = (not A) and (not B)

您的修复是 not (A or B),但您可以根据德摩根定律将其更改为 (not A) and (not B) 来修复它。