VB.Net - 赋值运算符



VB.Net 支持以下赋值运算符:

运算符 描述 示例
= 简单赋值运算符,将右侧操作数的值赋给左侧操作数 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
&= 将字符串表达式连接到字符串变量或属性,并将结果赋给该变量或属性。

Str1 &= Str2 等价于

Str1 = Str1 & Str2

示例

尝试以下示例以了解 VB.Net 中所有可用的赋值运算符:

Module assignment
   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
vb.net_operators.htm
广告