操作员 '!'不能应用于 x 类型的操作数

Operator '!' cannot be applied to operand of type x

所以我在 VB 中有一些代码,我正试图将其转换为 C#。这段代码是由其他人编写的,我试图理解它,但遇到了一些困难。我有一些按位运算符和枚举比较要做,但不断抛出错误:

我不能说我以前使用过很多这些语法,但我对如何编写这段代码感到困惑。我使用 Google 来了解更多相关信息,还使用 ​​VB 到 C# 在线转换器,希望获得一些基本指导,但一无所获。下面的代码

VB - 这是有效的原始代码

Flags = Flags And Not MyEnum.Value ' Flags is of type int

C# - 我转换的代码抛出错误

Flags = Flags & !MyEnum.Value; // Flags is of type int

Error - 每次返回的错误

Operator '!' cannot be applied to operand of type MyEnum'.

任何帮助和解释都将不胜感激。

您可能混淆了逻辑按位一元运算符

让我们访问帮助

Operators (C# Programming Guide)

一元运算符

  • +x身份
  • -x 取反
  • !x 逻辑非
  • ~x 按位取反
  • ++x预增
  • --x预减
  • (T)x 将 x 显式转换为类型 T

Compiler Error CS0023

Operator 'operator' cannot be applied to operand of type 'type'

An attempt was made to apply an operator to a variable whose type was not designed to work with the operator.

!只能对bool类型进行操作。您似乎在对某些位标志进行操作。在这种情况下,您应该使用按位 NOT 运算符 ~ 而不是逻辑 NOT 运算符 !:

Flags = Flags & ~((int)MyEnum.Value); // you need to cast to int as well

为了获得最佳转换,首先了解 VB 正在为您执行的隐式转换会有所帮助:

Flags = Flags And Not (CInt(MyEnum.Value))

这相当于 C# 代码:

Flags = Flags & ~(int)MyEnum.Value;

可以缩短的:

Flags &= ~(int)MyEnum.Value;

在 VB 中,"Not" 既是逻辑运算符又是按位运算符,具体取决于上下文,但在 C# 中,您有两个不同的运算符。