C#中的双按位NOT(~~) [英] Double bitwise NOT (~~) in C#
问题描述
我一直在阅读ThreadLocal<T>
的实现,并且在将int id存储在私有int字段(m_idComplement
)中然后将其几乎转换成几乎每个表达式之前都不太了解反转int id的原理.用于.除了适用于JavaScript的这种情况找到任何有关为什么在C#中双重否定会有用的信息吗?
I've been reading through ThreadLocal<T>
implementation and don't quite understand the rationale behind inverting an int id before storing it in a private int filed (m_idComplement
) and then inverting it back again in almost every expression it's used in. Except for this case applicable to JavaScript, I can't find any information on why would double negation be useful in C#?
在第240行,它确实分配了0,而没有取反,但是它本可以分配为-1,然后丢弃所有其他不必要的值,不是吗?
On line 240 it does assign 0 without negation, but it could've just assigned a -1 and just drop all the other unnecessary ones, no?
https://dl.dropboxusercontent.com/u/65419748/ThreadLocal.cs
https://i.imgur.com/3z3F64V.png
推荐答案
ThreadLocal.cs
的参考源对此字段包含以下注释:
The reference source for ThreadLocal.cs
contains the following comment against this field:
此ThreadLocal<>实例的插槽ID.我们存储ID的按位补码(即〜ID),这使我们能够区分ID为0的情况和未完全初始化的对象,这是由于构造函数中的线程中止,也可能是由于内存模型引起的用户代码中出现问题.
Slot ID of this ThreadLocal<> instance. We store a bitwise complement of the ID (that is ~ID), which allows us to distinguish between the case when ID is 0 and an incompletely initialized object, either due to a thread abort in the constructor, or possibly due to a memory model issue in user code.
本质上,他们将ID的默认未初始化值从0(如果直接作为int
字段直接存储,则应为0)切换为-1.
They're essentially switching the default, uninitialized value of the ID from 0, which it would be if stored directly as an int
field, to -1.
这篇关于C#中的双按位NOT(~~)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!