最近我从 VB 转到 C#,所以我经常使用 C# 到 VB.NET 的转换器来了解语法差异。在将下一个方法转移到 VB 时,我注意到一件有趣的事情。
C#原代码:
public bool ExceedsThreshold(int threshold, IEnumerable<bool> bools)
{
int trueCnt = 0;
foreach(bool b in bools)
if (b && (++trueCnt > threshold))
return true;
return false;
}
VB.NET 结果:
Public Function ExceedsThreshold(threshold As Integer, bools As IEnumerable(Of Boolean)) As Boolean
Dim trueCnt As Integer = 0
For Each b As Boolean In bools
If b AndAlso (System.Threading.Interlocked.Increment(trueCnt) > threshold) Then
Return True
End If
Next
Return False End Function
C#的++
操作符被替换为System.Threading.Interlocked.Increment
是否意味着++
如果在foreach
循环中使用不是线程安全的操作符成为线程安全的?它是一种语法糖吗?如果这是真的,那为什么转换器放在Interlocked.Increment
VB版本中呢?我认为 C# 和 VB 中的 foreach 工作方式完全相同。或者它只是一个转换器“保险”?