为什么要使用System.Threading.Interlocked.Decrement而不是减号? [英] Why use System.Threading.Interlocked.Decrement instead of minus?
问题描述
我将一些c#代码转换为vb.net,converter.telerik.com将其转换为:
I converted some c# code to vb.net and the converter.telerik.com turned this:
i--;
为此:
System.Math.Max(System.Threading.Interlocked.Decrement(i), i + 1)
所有的幻想如何?
推荐答案
MichałPiaskowski的评论触发了以下解释:
Michał Piaskowski's comment triggered the following explanation:
C#中 i-
的语义是返回 i的当前值
(即减量发生之前的值),然后将 i
减一。
The semantics of i--
in C# are to return the current value of i
(i.e., the value before the decrement occurs) and then decrement i
by one.
因此,我们需要将其转换为VB。我们不能使用 i-= 1
,因为这不会在减量前返回 i
的当前值。因此,我们需要一个操作,该操作将减小 i
但在减小之前返回 i
的值,例如: / p>
So, we need to convert that to VB. We can not use i -= 1
because this does not return the current value of i
before the decrement. So, we need an operation that will decrement i
but return the value of i
before the decrement, something like:
Function DoPostDecrement(ByRef i As Integer) As Integer
i -= 1
Return i + 1
End Function
但这建议使用以下内容以避免编写方法来执行上述操作:
But this suggests using the following to avoid having to write a method to perform the above:
System.Math.Max(
someValueThatIsEqualToiMinusOne,
someValueThatIsEqualtoiBeforeTheDecrement
)
但是VB.NET不允许您使用 i-= 1
或 i = i-1
代替 someValueThatIsEsEqualToiMinusOne
。但是, System.Threading.Interlocked.Decrement(i)
是合法的,并且等于 i-1
的值。完成此操作后,由于参数是从左到右计算的,因此 someValueThatIsEqualtoiBeforeTheDecrement
应该为 i + 1
(此时,递减到 i + 1
是递减前的值。
But VB.NET won't let you use i -= 1
or i = i - 1
in place of someValueThatIsEqualToiMinusOne
. However, System.Threading.Interlocked.Decrement(i)
is legit and equal to the value of i - 1
. Once you do that, because parameters are evaluated left to right, someValueThatIsEqualtoiBeforeTheDecrement
should be i + 1
(at that point the decrement has been performed to i + 1
is the pre-decrement value.
请注意,上述方法 DoPostDecrement
和 System.Math.Max,System.Threading.Interlocked.Decrement
构造在多线程上下文中可能具有不同的语义。
Note that the above method DoPostDecrement
and the System.Math.Max, System.Threading.Interlocked.Decrement
construct could have different semantics in a multithreaded context.
这篇关于为什么要使用System.Threading.Interlocked.Decrement而不是减号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!