Int*_*ble 4 vb.net bitwise-operators bitwise-and bitwise-xor
请注意下面的简单示例:
Module Module1
<Flags>
Public Enum Names
None = 0
Test = 1
Test2 = 2
Test3 = 4
Test4 = 8
End Enum
Sub Main()
Dim test As Names = Names.Test Or Names.Test3
If (test And Names.Test3) = Names.Test3
Console.WriteLine("TRUE")
Else
Console.WriteLine("FALSE")
End If
End Sub
End Module
Run Code Online (Sandbox Code Playgroud)
我的问题的第一部分与这条线有关If (test And Names.Test3) = Names.Test3。
仅仅检查If test And Names.Test3该标志是否存在会更好吗?如果它的计算结果为非零值(意味着该标志存在),那么条件的结果仍然是True。
是否有充分的理由使用第一种方法进行第二种检查?(虽然我的回答是针对VB.NET,但我也想知道这是否是其他地方(例如C#,C ++等)的潜在陷阱)。
此外,关于标记删除,似乎有两种方法可以执行此操作:
test = test Xor Names.Test3 和 test = test And Not Names.Test3
但是,如果缺少该标志,则第一个将添加该标志;如果存在该标志,则将其删除;而第二个将仅将其删除。那是唯一的区别吗?还是有另一个原因导致我比其他方法更喜欢一种方法?
您正确地说,您可以有效地代替它:
If (test And Names.Test3) = Names.Test3 Then
有了这个
If (test And Names.Test3) Then
但是,第二个示例无法Option Strict On正确编译,因为您正确地得到了错误:
Option Strict On disallows implicit conversions from 'Names' to 'Boolean'因此,为了使其能够编译,您需要对其进行包装CBool。
因此,总而言之,我想说第一个示例会更好,因为其意图非常明确:-您正在检查是否设置了位。
关于标记删除,即取消设置,您应该使用:
test = test And Not Names.Test3
使用Xor具有切换值的效果。
以下内容可能会有所帮助(特别是如果您使它们成为扩展方法):
Public Function SetBit(ByVal aValue As Names, ByVal aBit As Names) As Names
Return (aValue Or aBit)
End Function
Public Function ClearBit(ByVal aValue As Names, ByVal aBit As Names) As Names
Return (aValue And Not aBit)
End Function
Public Function IsBitSet(ByVal aValue As Names, ByVal aBit As Names) As Boolean
Return ((aValue And aBit) = aBit)
End Function
Public Function ToggleBit(ByVal aValue As Names, ByVal aBit As Names) As Names
Return (aValue Xor aBit)
End Function
Run Code Online (Sandbox Code Playgroud)