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 的所有赋值运算符:
Module assignmentOp
Sub Main()
Dim a As Integer = 21
Dim pow As Integer = 2
Dim str1 As String = "Hello! "
Dim str2 As String = "VB Programmers"
Dim c As Integer
c = a
Console.WriteLine("Line 1 - = Operator Example, Value of c = {0}", c)
c += a
Console.WriteLine("Line 2 - += Operator Example, Value of c = {0}", c)
c -= a
Console.WriteLine("Line 3 - -= Operator Example, Value of c = {0}", c)
c *= a
Console.WriteLine("Line 4 - *= Operator Example, Value of c = {0}", c)
c /= a
Console.WriteLine("Line 5 - /= Operator Example, Value of c = {0}", c)
c = 20
c ^= pow
Console.WriteLine("Line 6 - ^= Operator Example, Value of c = {0}", c)
c <<= 2
Console.WriteLine("Line 7 - <<= Operator Example, Value of c = {0}", c)
c >>= 2
Console.WriteLine("Line 8 - >>= Operator Example, Value of c = {0}", c)
str1 &= str2
Console.WriteLine("Line 9 - &= Operator Example, Value of str1 = {0}", str1)
Console.ReadLine()
End Sub
End Module
结果如下:
Line 1 - = Operator Example, Value of c = 21
Line 2 - += Operator Example, Value of c = 42
Line 3 - -= Operator Example, Value of c = 21
Line 4 - *= Operator Example, Value of c = 441
Line 5 - /= Operator Example, Value of c = 21
Line 6 - ^= Operator Example, Value of c = 400
Line 7 - <<= Operator Example, Value of c = 1600
Line 8 - >>= Operator Example, Value of c = 400
Line 9 - &= Operator Example, Value of str1 = Hello! VB Programmers