跳转到内容

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)

请注意最后两个运算符的顺序,将它们颠倒是不合法的。

华夏公益教科书