[英]Operator '!' cannot be applied to operand of type x
So I have some code in VB that I am trying to convert to C#. 所以我在VB中有一些代码,我试图转换为C#。 This code was written by someone else and I am trying to understand it but with some difficulty.
这段代码是由其他人编写的,我试图理解它,但有些困难。 I have some bitwise operator and enum comparison to do but keep throwing an error out:
我有一些按位运算符和枚举比较,但不断抛出错误:
I cannot say that i have used a lot of these syntaxes before and am baffled how to write this code. 我不能说我之前使用了很多这些语法,并且对如何编写此代码感到困惑。 I have used Google to understand more about it and also used VB to C# online converters in the hopes of getting some basic guidance but nothing.
我已经使用谷歌了解了它的更多信息,并且还使用了VB到C#在线转换器,希望得到一些基本的指导,但没有。 The code below
下面的代码
VB - This is the original code that works VB - 这是有效的原始代码
Flags = Flags And Not MyEnum.Value ' Flags is of type int
C# -the code I converted which is throwing an error C# - 我转换的代码,它抛出一个错误
Flags = Flags & !MyEnum.Value; // Flags is of type int
Error - The error that is returned every time 错误 - 每次返回的错误
Operator '!'
接线员'!' cannot be applied to operand of type MyEnum'.
不能应用于MyEnum类型的操作数。
Any help and some explanation on this will be greatly appreciated. 任何帮助和一些解释将非常感谢。
!
can only operate on bool
type. 只能在
bool
类型上运行。 You seem to be operating on some bit flags. 你似乎在操作一些位标志。 In that case you should use the bitwise NOT operator
~
instead of the logical NOT operator !
在这种情况下,您应该使用按位NOT运算符
~
而不是逻辑NOT运算符!
: :
Flags = Flags & ~((int)MyEnum.Value); // you need to cast to int as well
To get the best conversion, it helps to first understand the implicit conversion that VB is doing for you: 要获得最佳转换,首先要了解VB为您执行的隐式转换是有帮助的:
Flags = Flags And Not (CInt(MyEnum.Value))
This is equivalent to the C# code: 这相当于C#代码:
Flags = Flags & ~(int)MyEnum.Value;
Which can be shortened: 哪个可以缩短:
Flags &= ~(int)MyEnum.Value;
In VB, "Not" is both the logical and bitwise operator, depending on context, but in C# you have two distinct operators. 在VB中,“Not”既是逻辑运算符又是按位运算符,具体取决于上下文,但在C#中,您有两个不同的运算符。
You maybe confusing Logical and Bitwise unary operators 你可能会混淆Logical和Bitwise一元运算符
Lets visit the help 让我们访问帮助
Operators (C# Programming Guide) 运算符(C#编程指南)
Unary Operators 一元运算符
+x
Identity +x
身份 -x
Negation -x
否定 !x
Logical negation !x
逻辑否定 ~x
Bitwise negation ~x
按位否定 ++x
Pre-increment ++x
预增量 --x
Pre-decrement --x
预先减少 (T)x
Explicitly convert x to type T (T)x
将x显式转换为T型 Compiler Error CS0023 编译器错误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.
尝试将运算符应用于其类型未设计为与运算符一起使用的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.