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
廣告

© . All rights reserved.