编译器通过移位操作将按位与添加到表达式树中
Compiler adding bitwise AND into expression tree with bit-shifting operation
我希望得到以下代码:
Dim i = 7, j = 5
Dim expr As Expression(Of Func(Of Integer)) = Function() i << j
在i
和j
两个变量之间进行一次运算,生成LambdaExpression
的表达式树。相反,表达式树包含针对 31
的额外按位 &
操作,如以下 DebugView 所示:
.Lambda #Lambda1<System.Func`1[System.Int32]>() {
.Constant<_visualizerTests.VB.Module1+_Closure$__0-0>(_visualizerTests.VB.Module1+_Closure$__0-0).$VB$Local_i << (.Constant<_visualizerTests.VB.Module1+_Closure$__0-0>(_visualizerTests.VB.Module1+_Closure$__0-0).$VB$Local_j &
31)
}
或者,visually:
使用右移时会引入相同的操作。
C# 编译器似乎没有相同的行为 -- 左移和右移运算符都不会导致编译器引入任何额外的操作。
为什么要引入这个附加操作?
来自docs:
To prevent a shift by more bits than the result can hold, Visual Basic masks the value of amount
with a size mask that corresponds to the data type of pattern
. The binary AND
of these values is used for the shift amount.
我希望得到以下代码:
Dim i = 7, j = 5
Dim expr As Expression(Of Func(Of Integer)) = Function() i << j
在i
和j
两个变量之间进行一次运算,生成LambdaExpression
的表达式树。相反,表达式树包含针对 31
的额外按位 &
操作,如以下 DebugView 所示:
.Lambda #Lambda1<System.Func`1[System.Int32]>() {
.Constant<_visualizerTests.VB.Module1+_Closure$__0-0>(_visualizerTests.VB.Module1+_Closure$__0-0).$VB$Local_i << (.Constant<_visualizerTests.VB.Module1+_Closure$__0-0>(_visualizerTests.VB.Module1+_Closure$__0-0).$VB$Local_j &
31)
}
或者,visually:
使用右移时会引入相同的操作。
C# 编译器似乎没有相同的行为 -- 左移和右移运算符都不会导致编译器引入任何额外的操作。
为什么要引入这个附加操作?
来自docs:
To prevent a shift by more bits than the result can hold, Visual Basic masks the value of
amount
with a size mask that corresponds to the data type ofpattern
. The binaryAND
of these values is used for the shift amount.