Why can't we lock on a value type?

前端 未结 9 1096
天涯浪人
天涯浪人 2020-12-08 06:27

I was trying to lock a Boolean variable when I encountered the following error :

\'bool\' is not a reference type as require

9条回答
  •  青春惊慌失措
    2020-12-08 07:05

    Just a wild guess here...

    but if the compiler let you lock on a value type, you would end up locking nothing at all... because each time you passed the value type to the lock, you would be passing a boxed copy of it; a different boxed copy. So the locks would be as if they were entirely different objects. (since, they actually are)

    Remember that when you pass a value type for a parameter of type object, it gets boxed (wrapped) into a reference type. This makes it a brand-new object each time this happens.

提交回复
热议问题