问题描述
对于以下代码,我得到一个编译时错误,*
For the following code I get a compile time error, *
int i = 0;
lock(i);
但没有错误:
int i = 0;
Monitor.Enter(i);
我知道,由于拳击引起的复杂性,不应将值类型用于锁定.但是,为什么它可以与Monitor一起使用.
I understand that a value type shouldn't be used for locking due to the complications arising due to boxing. But, then why does it work with Monitor.
推荐答案
之所以如此,是因为锁是一种语言构造,编译器选择在表达式上加上额外的语义. Monitor.Enter只是方法调用,而C#编译器在任何情况下都不对调用进行特殊处理,因此它会通过正常的重载解析和装箱进行处理.
The reason why is that lock is a language construct and compiler chooses to impose extra semantics on the expression. Monitor.Enter is simply a method call and the C# compiler does not special case the call in any way and hence it goes through normal overload resolution and boxing.
这篇关于为什么不允许使用lock(< integer var>),但允许Monitor.Enter(< integer var>)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!