2017-05-05 63 views
3

在仔細閱讀了^ (hat) operatorMath.Pow()函數的MSDN文檔後,我發現沒有明顯區別。有一個嗎?Hat ^運算符與Math.Pow()

顯然存在不同之處,一個是功能而另一個被認爲是操作員,例如,這是行不通的:

Public Const x As Double = 3 
Public Const y As Double = Math.Pow(2, x) ' Fails because of const-ness 

但這會:

Public Const x As Double = 3 
Public Const y As Double = 2^x 

但是,有沒有在如何產生的最終結果有區別嗎?例如Math.Pow()做更多的安全檢查?或者僅僅是另一種別名?

回答

5

找出的一種方法是檢查IL。爲:

Dim x As Double = 3 
Dim y As Double = Math.Pow(2, x) 

的IL是:

IL_0000: nop   
IL_0001: ldc.r8  00 00 00 00 00 00 08 40 
IL_000A: stloc.0  // x 
IL_000B: ldc.r8  00 00 00 00 00 00 00 40 
IL_0014: ldloc.0  // x 
IL_0015: call  System.Math.Pow 
IL_001A: stloc.1  // y 

而對於:

Dim x As Double = 3 
Dim y As Double = 2^x 

的IL 是:

IL_0000: nop   
IL_0001: ldc.r8  00 00 00 00 00 00 08 40 
IL_000A: stloc.0  // x 
IL_000B: ldc.r8  00 00 00 00 00 00 00 40 
IL_0014: ldloc.0  // x 
IL_0015: call  System.Math.Pow 
IL_001A: stloc.1  // y 

IE編譯器已接通^調用Math.Pow - 它們在運行時是相同的。

+0

太好了,謝謝。如何檢查IL(在VS2017中)? – Toby

+2

在VS中無法確定 - 我個人只是將這樣的片段嵌入[LINQPad](https://www.linqpad.net/),就像[this]一樣(https://i.stack.imgur.com/ZRO4F.png )。 –

+0

酷,FYI我剛剛發現https://dotnetfiddle.net/,但類似但在線,也顯示IL :-) – Toby