跳轉到內容

Visual Basic .NET/賦值和比較運算子

來自華夏公益教科書,開放的書籍,開放的世界

"=" 運算子用於賦值。該運算子也用作比較運算子(參見比較)。

  • 設定值
  x = 7     ' x is now seven; in math terms we could say "let x = 7"
  x = -1294
  x = "example"

您也可以在等號運算子中使用變數。

  Dim x As Integer
  Dim y As Integer = 4
  x = y  ' Anywhere we use x, 4 will be used.
  y = 5  ' Anywhere we use y, 5 will be used, x stays to 4

"=" 運算子用於比較。該運算子也用作賦值運算子(參見賦值)。

  • 比較值
  If 4 = 9 Then       ' This code will never happen:
    End  ' Exit the program.
  End If
  If 1234 = 1234 Then ' This code will always be run after the check:
    MessageBox.Show("Wow!  1234 is the same as 1234.") 
      ' Create a box in the center of the screen.
  End If

您也可以在等號運算子中使用變數。

  If x = 4 Then
    MessageBox.Show("x is four.")
  End If

讓我們嘗試一個稍微更高階的操作。

  MessageBox.Show("Seven equals two is " & (7 = 2) & ".")
  ' The parentheses are used because otherwise, by order of operations (equals is 
  ' processed last), it would be comparing the strings "Seven equals two is 7" and "2.".
  ' Note here that the & operator appends to the string.  We will talk about this later.
  '
  '  The result of this should be a message box popping up saying "Seven equals two is
  '   False."   This is because (7 = 2) will return False anywhere you put it.  In the
  '   same sense, (7 = 7) will return True:
  MessageBox.Show("Seven equals seven is " & (7 = 7) & ".")

如果您嘗試為常量或字面量賦值,例如 7 = 2,您將收到錯誤。您可以比較 7 和 2,但答案將始終為 False

在語句中出現兩個等號運算子的情況下,例如

  Dim x As Boolean
  x = 2 = 7

第二個等號運算子將首先被處理,比較 2 和 7,得到 False。然後第一個等號運算子將被處理,將 False 賦值給 x。

更多比較運算子

[編輯 | 編輯原始碼]
 (x < y)  (x > y)  (x <> y)  (x <= y)  (x >= y)

(x 小於 y),(x 大於 y),(x 不等於 y),(x 小於或等於 y) & (x 大於或等於 y)

請注意最後兩個運算子的順序,將它們顛倒是不合法的。

華夏公益教科書