Visual Basic 赋值运算符

基本的赋值运算符是 "="。他的优先级别低于其他的运算符,所以对该运算符往往最后读取。

VB 支持下列赋值运算符:

运算符描述说明
=简单赋值操作符,将右侧操作数的值赋给左侧操作数C = A + B 将把 A + B 的值赋值给 C
+=添加和赋值操作符,它将右操作数添加到左操作数,并将结果赋给左操作数C += A 等效于 C = C + A
-=减去和赋值运算符,从左边的操作数中减去右边的操作数,并将结果赋给左边的操作数C -= A 等效于 C = C - A
*=乘法和赋值运算符,它将右操作数与左操作数相乘,并将结果赋给左操作数C *= A 等效于 C = C * A
/=除法和赋值运算符,用左操作数和右运算数分开,赋值给左操作数(浮点除法)C /= A 等效于 C = C / A
\=除法和赋值运算符,用左操作数除以右操作数,并将结果赋给左操作数(整数除法)C \= A 等效于 C = C \A
^=指数运算和赋值运算符。它将左操作数指定的右操作数指数的幂值,并将结果赋给左操作数。C^=A 等效于 C = C ^ A
<<=左移和赋值运算符C <<= 2 等效于 C = C << 2
>>=右移和赋值运算符C >>= 2 等效于 C = C >> 2
&=将一个字符串(String)表达式连接到一个字符串(String)变量或属性,并将结果赋给变量或属性。Str1 &= Str2 等效于 Str1 = Str1 & Str2

实例

尝试下面的例子来理解 VB 的所有赋值运算符:

  1. Module assignmentOp
  2. Sub Main()
  3. Dim a As Integer = 21
  4. Dim pow As Integer = 2
  5. Dim str1 As String = "Hello! "
  6. Dim str2 As String = "VB Programmers"
  7. Dim c As Integer
  8. c = a
  9. Console.WriteLine("Line 1 - = Operator Example, Value of c = {0}", c)
  10. c += a
  11. Console.WriteLine("Line 2 - += Operator Example, Value of c = {0}", c)
  12. c -= a
  13. Console.WriteLine("Line 3 - -= Operator Example, Value of c = {0}", c)
  14. c *= a
  15. Console.WriteLine("Line 4 - *= Operator Example, Value of c = {0}", c)
  16. c /= a
  17. Console.WriteLine("Line 5 - /= Operator Example, Value of c = {0}", c)
  18. c = 20
  19. c ^= pow
  20. Console.WriteLine("Line 6 - ^= Operator Example, Value of c = {0}", c)
  21. c <<= 2
  22. Console.WriteLine("Line 7 - <<= Operator Example, Value of c = {0}", c)
  23. c >>= 2
  24. Console.WriteLine("Line 8 - >>= Operator Example, Value of c = {0}", c)
  25. str1 &= str2
  26. Console.WriteLine("Line 9 - &= Operator Example, Value of str1 = {0}", str1)
  27. Console.ReadLine()
  28. End Sub
  29. End Module

结果如下:

  1. Line 1 - = Operator Example, Value of c = 21
  2. Line 2 - += Operator Example, Value of c = 42
  3. Line 3 - -= Operator Example, Value of c = 21
  4. Line 4 - *= Operator Example, Value of c = 441
  5. Line 5 - /= Operator Example, Value of c = 21
  6. Line 6 - ^= Operator Example, Value of c = 400
  7. Line 7 - <<= Operator Example, Value of c = 1600
  8. Line 8 - >>= Operator Example, Value of c = 400
  9. Line 9 - &= Operator Example, Value of str1 = Hello! VB Programmers

分类导航