下表顯示了VB.Net支持的所有邏輯運算符。 假設(shè)變量A為布爾值True,變量B為布爾值False,則:
運算符 | 描述 | 實例 |
---|---|---|
And | 它是邏輯運算符,也是按位與運算符。如果兩個操作數(shù)都為真,則條件為真。該運算符不執(zhí)行短路操作,即同時計算兩個表達(dá)式。(該運算符又被稱為與運算符,只有兩邊都為真時返回結(jié)果才能為真) | (A And B) 返回 False. |
Or | 它既是邏輯運算符,也是按位或運算符。如果兩個操作數(shù)中的任何一個為真,則條件為真。該運算符不執(zhí)行短路操作,即同時計算兩個表達(dá)式。(該運算符又被稱為或運算符,只有兩邊都為假時返回的結(jié)果才能為假) | (A Or B) 返回 True. |
Not | 它既是邏輯運算符,也是按位非運算符。 用于反轉(zhuǎn)其操作數(shù)的邏輯狀態(tài)。 如果條件為真,則邏輯非運算符將為假。(該運算符又被稱為非運算符,用于反轉(zhuǎn)邏輯狀態(tài)) | Not(A And B) 返回True. |
Xor | 它是邏輯和按位邏輯異或運算符。如果兩個表達(dá)式都為真或都為假,則返回True;否則,它返回False。該運算符不執(zhí)行短路,它總是計算兩個表達(dá)式,并且沒有該運算符的短路對應(yīng)項 (異或運算的特點是:只有兩個表達(dá)式結(jié)果不同才會返回真) | A Xor B 返回 True. |
AndAlso | 它是邏輯AND運算符。它只對布爾數(shù)據(jù)有效。它執(zhí)行短路。 | (A AndAlso B) 返回 False. |
OrElse | 它是邏輯或運算符。 它只適用于布爾數(shù)據(jù)。 它執(zhí)行短路。 | (A OrElse B) 返回 True. |
IsFalse | 它確定表達(dá)式是否為False。 | |
IsTrue | 它確定表達(dá)式是否為True。 |
短路運算:一種邏輯運算規(guī)則,我們知道與邏輯運算的算法是只要有一個假就能判定為假,或運算符只要有一個為真就能判定為真。短路運算的算法就是建立在這一基礎(chǔ)上。
以與運算為例:當(dāng)兩個表達(dá)式前一個表達(dá)式判定為假時,第二個表達(dá)式不會進行計算,直接返回假
這樣的計算被稱為短路運算,它可以提高邏輯運算的速度(畢竟有一部分情況只需要計算第一個表達(dá)式即可)
但是短路運算也有其缺點,就是不夠嚴(yán)謹(jǐn),特別是部分情況下還是需要運算第二個表達(dá)式。所以很多語言都有提供短路版本和非短路版本的與運算和或運算。
嘗試以下示例來了解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
'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
當(dāng)上述代碼被編譯和執(zhí)行時,它產(chǎn)生以下結(jié)果:
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
更多建議: