Visual Basic 逻辑运算符
逻辑运算符,它把语句连接成更复杂的复杂语句。
逻辑运算符包括,逻辑 NOT,逻辑 AND,逻辑 OR 等。
优先级为:NOT AND OR 同级运算从左到右。
下表显示了 VB 支持的所有逻辑运算符。假设变量 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 中可用的所有逻辑/位运算符:
Module logicalOpSub Main()Dim a As Boolean = TrueDim b As Boolean = TrueDim c As Integer = 5Dim d As Integer = 20'logical And, Or and Xor CheckingIf (a And b) ThenConsole.WriteLine("Line 1 - Condition is true")End IfIf (a Or b) ThenConsole.WriteLine("Line 2 - Condition is true")End IfIf (a Xor b) ThenConsole.WriteLine("Line 3 - Condition is true")End If'bitwise And, Or and Xor Checking'If (c And d) ThenConsole.WriteLine("Line 4 - Condition is true")End IfIf (c Or d) ThenConsole.WriteLine("Line 5 - Condition is true")End IfIf (c Or d) ThenConsole.WriteLine("Line 6 - Condition is true")End If'Only logical operatorsIf (a AndAlso b) ThenConsole.WriteLine("Line 7 - Condition is true")End IfIf (a OrElse b) ThenConsole.WriteLine("Line 8 - Condition is true")End If' lets change the value of a and b 'a = Falseb = TrueIf (a And b) ThenConsole.WriteLine("Line 9 - Condition is true")ElseConsole.WriteLine("Line 9 - Condition is not true")End IfIf (Not (a And b)) ThenConsole.WriteLine("Line 10 - Condition is true")End IfConsole.ReadLine()End SubEnd Module
结果如下:
Line 1 - Condition is trueLine 2 - Condition is trueLine 4 - Condition is trueLine 5 - Condition is trueLine 6 - Condition is trueLine 7 - Condition is trueLine 8 - Condition is trueLine 9 - Condition is not true