下表显示了VB.Net支持的所有逻辑运算符。假设变量A = True
,变量B = False
,则:
运算符 | 描述 | 说明 |
---|---|---|
And |
它是逻辑运算符,也是按位运算符。如果两个操作数都是:True ,则条件成立。 该运算符不执行短路,即它评估两个表达式的值。 |
(A And B) 结果为:False |
Or |
它是逻辑以及按位或运算符。如果两个操作数中的任何一个为True ,则条件成立。 该运算符不执行短路,即它评估两个表达式。 |
(A Or B) 结果为:True |
Not |
它是逻辑,也是按位运算符。用于反转其操作数的逻辑状态。如果条件成立,那么逻辑非运算符结果为:False 。 |
Not(A And B) 结果为:True |
Xor |
它是逻辑,也是按位的逻辑异或运算符。 如果两个表达式均为True 或两个表达式均为False ,则返回True ; 否则返回False 。 该运算符不执行短路,它总是评估这两个表达式,并且没有短路对应。 |
A Xor B 结果为:True |
AndAlso |
这是逻辑AND 运算符,它只适用于布尔数据,并可执行短路。 |
(A AndAlso B) 结果为:False |
OrElse |
这是合乎逻辑的OR 运算符,它只适用于布尔数据,并可执行短路。 |
(A OrElse B) 结果为:True |
IsFalse |
它确定一个表达式是否为False 。 |
|
IsTrue |
它确定一个表达式是否为True 。 |
示例
尝试下面的例子来理解VB.Net中可用的所有逻辑/位运算符:
文件:logicalOp.vb -
Module logicalOp
Sub Main()
Dim a As Boolean = True
Dim b As Boolean = True
Dim c As Integer = 5
Dim d As Integer = 20
'logical And, Or and Xor Checking
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
'bitwise And, Or and Xor Checking'
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
' lets change the value of a and 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
执行上面示例代码,得到以下结果 -
F:\worksp\vb.net\operators>vbc logicalOp.vb
F:\worksp\vb.net\operators>logicalOp.exe
Line 1 - Condition is true
Line 2 - 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
上一篇:
VB.Net运算符
下一篇:
VB.Net决策结构