Tob*_*oby 3 .net vb.net exponentiation pow
仔细阅读了^(hat)运算符和Math.Pow()函数的MSDN文档后,我发现没有明显的区别.有吗?
显然有一个区别是一个是一个函数而另一个被认为是一个运算符,例如这不起作用:
Public Const x As Double = 3
Public Const y As Double = Math.Pow(2, x) ' Fails because of const-ness
Run Code Online (Sandbox Code Playgroud)
但这会:
Public Const x As Double = 3
Public Const y As Double = 2^x
Run Code Online (Sandbox Code Playgroud)
但他们如何产生最终结果有所不同吗?是否Math.Pow()做更多的安全检查例子吗?或者只是另一种别名的某种别名?
找出答案的一种方法是检查IL.对于:
Dim x As Double = 3
Dim y As Double = Math.Pow(2, x)
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
并为:
Dim x As Double = 3
Dim y As Double = 2 ^ x
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
IE编译器已将其^转换为调用Math.Pow- 它们在运行时是相同的.