VB.Net - 邏輯/按位運算子



下表顯示了 VB.Net 支援的所有邏輯運算子。假設變數 A 持有布林值 True,變數 B 持有布林值 False,則 -

運算子 描述 示例
And 它是邏輯運算子和按位 AND 運算子。如果兩個運算元都為真,則條件變為真。此運算子不執行短路,即它評估兩個表示式。 (A And B) 為 False。
Or 它是邏輯運算子和按位 OR 運算子。如果兩個運算元中的任何一個為真,則條件變為真。此運算子不執行短路,即它評估兩個表示式。 (A Or B) 為 True。
Not 它是邏輯運算子和按位 NOT 運算子。用於反轉其運算元的邏輯狀態。如果條件為真,則邏輯 NOT 運算子將變為假。 Not(A And B) 為 True。
Xor 它是邏輯運算子和按位異或運算子。如果兩個表示式都為真或兩個表示式都為假,則返回 False;否則,返回 True。此運算子不執行短路,它始終評估兩個表示式,並且此運算子沒有短路對應項 A Xor B 為 True。
AndAlso 它是邏輯 AND 運算子。它僅適用於布林資料。它執行短路。 (A AndAlso B) 為 False。
OrElse 它是邏輯 OR 運算子。它僅適用於布林資料。它執行短路。 (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
      '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

編譯並執行上述程式碼時,將產生以下結果 -

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
vb.net_operators.htm
廣告

© . All rights reserved.