2017-05-05 21 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