C#: In what cases should you null out references?

后端 未结 3 1017
情话喂你
情话喂你 2021-02-14 05:39

The CLR Profiler can also reveal which methods allocate more storage than you expected, and can uncover cases where you inadvertently keep references to useless o

3条回答
  •  离开以前
    2021-02-14 06:36

    You only need to do it when the variable holding the reference is going to stay "alive" but you don't want the reference itself to prevent garbage collection. In other words, if object A holds a reference to object B, and you don't need B any more but A will stay alive for other reasons. Another common example is static variables, which are "alive" for as long as the AppDomain is.

    For local variables it's almost never needed, because the GC can detect the last possible point in code where a variable will be accessed. However, if you use a variable declared outside a loop during the first iteration, but you know you won't need it for subsequent iterations, you could set that to null to help the object to become eligible for GC earlier.

    In my experience it's very rare to find myself in this situation. I hardly ever deliberate set variables to null for the sake of the GC. Usually all the member variables within an object are "useful" until the object itself becomes eligible for GC. If you find yourself with member variables which aren't useful for the whole lifetime of the object, you might want to see whether that indicates a problem with the design.

提交回复
热议问题