简体   繁体   English

C#中的双位NOT(~~)

[英]Double bitwise NOT (~~) in 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#? 我一直在阅读ThreadLocal<T>实现,并且在将它存储在私有int m_idComplementm_idComplement )之前反转int id然后在几乎每个它使用的表达式中再次反转它的基本原理之后并不完全理解。对于适用于JavaScript的这种情况 ,我找不到任何关于为什么双重否定在C#中有用的信息?

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? 在第240行,它确实分配0而没有否定,但是它可以只分配一个-1并且只丢弃所有其他不必要的那些,不是吗?

https://dl.dropboxusercontent.com/u/65419748/ThreadLocal.cs https://dl.dropboxusercontent.com/u/65419748/ThreadLocal.cs

https://i.imgur.com/3z3F64V.png https://i.imgur.com/3z3F64V.png

在此输入图像描述

The reference source for ThreadLocal.cs contains the following comment against this field: ThreadLocal.cs参考源包含针对此字段的以下注释:

Slot ID of this ThreadLocal<> instance. 此ThreadLocal <>实例的插槽ID。 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的按位补码(即~ID),这允许我们区分ID为0的情况和未完全初始化的对象,这可能是由于构造函数中的线程中止,或者可能是由于内存模型用户代码中的问题。

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. 它们本质上是将ID的默认未初始化值从0切换到-1,如果直接存储为int字段,则将其作为-1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM