VB.Net - 逻辑/位运算符
下表显示了VB.Net支持的所有逻辑运算符。 假设变量 A 持有布尔值 True,变量 B 持有布尔值 False,则 −
| 运算符 | 描述 | 示例 |
|---|---|---|
| And | 它是逻辑运算符以及按位与运算符。 如果两个操作数都为 true,则条件为 true。 该运算符不执行短路,即它计算两个表达式。 | (A And B)为 False。 |
| Or | 它是逻辑运算符和按位或运算符。 如果两个操作数中的任何一个为 true,则条件为 true。 该运算符不执行短路,即它计算两个表达式。 | (A Or B) 为 True。 |
| Not | 它是逻辑运算符和按位非运算符。 用于反转其操作数的逻辑状态。 如果条件为 true,则逻辑 NOT 运算符将使 false。 | Not(A And B) 为 True。 |
| Xor | 它是逻辑运算符以及按位逻辑异或运算符。 如果两个表达式都为 True 或两个表达式都为 False,则返回 False; 否则,返回 True。 该运算符不执行短路,它始终计算两个表达式,并且没有该运算符的短路对应项 | A Xor B 为 True。 |
| AndAlso | 它是逻辑AND运算符。 它仅适用于布尔数据。 它执行短路。 | (A AndAlso B) 为 False。 |
| OrElse | 它是逻辑或运算符。 它仅适用于布尔数据。 它执行短路。 | (A OrElse B) 为 True。 |
| IsFalse | 它确定表达式是否为 False。 | |
| IsTrue | 它确定表达式是否为 True。 |
尝试以下示例来了解 VB.Net 中可用的所有逻辑/位运算符 −
Module logicalOp
Sub Main()
Dim a As Boolean = True
Dim b As Boolean = True
Dim c As Integer = 5
Dim d As Integer = 20
'逻辑"与"、"或"和"异或"检查
If (a And b) Then
Console.WriteLine("Line 1 - Condition is true")
End If
If (a Or b) Then
Console.WriteLine("Line 2 - Condition is true")
End If
If (a Xor b) Then
Console.WriteLine("Line 3 - Condition is true")
End If
'按位与、或和异或检查
If (c And d) Then
Console.WriteLine("Line 4 - Condition is true")
End If
If (c Or d) Then
Console.WriteLine("Line 5 - Condition is true")
End If
If (c Or d) Then
Console.WriteLine("Line 6 - Condition is true")
End If
'Only logical operators
If (a AndAlso b) Then
Console.WriteLine("Line 7 - Condition is true")
End If
If (a OrElse b) Then
Console.WriteLine("Line 8 - Condition is true")
End If
' 改变 a 和 b 的值
a = False
b = True
If (a And b) Then
Console.WriteLine("Line 9 - Condition is true")
Else
Console.WriteLine("Line 9 - Condition is not true")
End If
If (Not (a And b)) Then
Console.WriteLine("Line 10 - Condition is true")
End If
Console.ReadLine()
End Sub
End Module
当上面的代码被编译并执行时,会产生以下结果 −
Line 1 - Condition is true Line 2 - Condition is true Line 3 - Condition is true Line 4 - Condition is true Line 5 - Condition is true Line 6 - Condition is true Line 7 - Condition is true Line 8 - Condition is true Line 9 - Condition is not true Line 10 - Condition is true

