Hat ^ operator vs Math.Pow()

时间:2017-05-05 12:23:44

标签: .net vb.net pow exponentiation

仔细阅读了^ (hat) operatorMath.Pow()函数的MSDN文档后,我发现没有明显的区别。有吗?

显然存在差异,一个是功能而另一个是运营商,例如这不起作用:

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()是否会进行更多安全检查?或者只是另一种别名的某种别名?

1 个答案:

答案 0 :(得分: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的调用 - 它们在运行时是相同的。