VB.Net - 運算子優先順序



運算子優先順序決定了表示式中項的組合方式。這會影響表示式的計算方式。某些運算子比其他運算子具有更高的優先順序;例如,乘法運算子的優先順序高於加法運算子。

例如,x = 7 + 3 * 2; 這裡,x 被賦值為 13,而不是 20,因為運算子 * 的優先順序高於 +,所以它首先計算 3*2,然後加上 7。

這裡,優先順序最高的運算子出現在表的最上面,優先順序最低的出現在最下面。在一個表示式中,優先順序更高的運算子將首先被計算。

運算子 優先順序
Await 最高
指數運算 (^)
一元標識和否定 (+, -)
乘法和浮點除法 (*, /)
整數除法 (\)
取模運算 (Mod)
加法和減法 (+, -)
算術位移 (<<, >>)
所有比較運算子 (=, <>, <, <=, >, >=, Is, IsNot, Like, TypeOf...Is)
否定 (Not)
連線 (And, AndAlso)
包含或 (Or, OrElse)
異或 (Xor) 最低

示例

以下示例以簡單的方式演示了運算子優先順序:

Module assignment
   Sub Main()
      Dim a As Integer = 20
      Dim b As Integer = 10
      Dim c As Integer = 15
      Dim d As Integer = 5
      Dim e As Integer
      e = (a + b) * c / d      ' ( 30 * 15 ) / 5
      
      Console.WriteLine("Value of (a + b) * c / d is : {0}", e)
      e = ((a + b) * c) / d    ' (30 * 15 ) / 5
      
      Console.WriteLine("Value of ((a + b) * c) / d is  : {0}", e)
      e = (a + b) * (c / d)   ' (30) * (15/5)
      
      Console.WriteLine("Value of (a + b) * (c / d) is  : {0}", e)
      e = a + (b * c) / d     '  20 + (150/5)
      
      Console.WriteLine("Value of a + (b * c) / d is  : {0}", e)
      Console.ReadLine()
   End Sub
End Module

當以上程式碼編譯並執行時,會產生以下結果:

Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is  : 90
Value of (a + b) * (c / d) is  : 90
Value of a + (b * c) / d is  : 50
vb.net_operators.htm
廣告

© . All rights reserved.