EDIT: While the original answer below is still accurate, it looks like it's the mixture of debug information and optimization which makes a difference here.
From my experiments:
Compiler flags Result
/o+ /debug- Finalizer runs
/o+ /debug+ Finalizer runs
/o- /debug- Finalizer runs
/o- /debug+ Finalizer does *not* run
The finalizer is still called on my box, when compiling on the command line with /o+
. My guess is that you're running in a debugger - which changes the GC behaviour. Without the debugger, the GC will collect anything that it can prove will never be read. With the debugger, I believe the GC won't collect any objects which still have references on the stack, even if there's no code to read the variables in question.
Now with an object initializer, the compiler code includes an extra reference on the stack. This line:
Zombie z = new Zombie { Name = "Guy" };
is effectively:
Zombie tmp = new Zombe();
tmp.Name = "Guy";
Zombie z = tmp;
The assignment to z
is only performed after all the properties have been set.
My guess is that the tmp
variable here is keeping the object alive.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…