Resurrection difference in using Object Initializer

后端 未结 2 1250
独厮守ぢ
独厮守ぢ 2020-12-07 02:11

I have this code:

Essentially i\'m trying to demonstrate the use of the c# finalizer and make an object that cannot die, I called it Zombie. Now, normally this demo

2条回答
  •  爱一瞬间的悲伤
    2020-12-07 02:32

    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.

提交回复
热议问题