Count number of objects of class type within class method

前端 未结 4 1478
北恋
北恋 2021-01-16 04:43

How can I count the number of objects of a class type within a method of that class? For that matter, how to do it outside of a class without adding the objects to a list?

4条回答
  •  走了就别回头了
    2021-01-16 05:11

    Do you mean in a way that would allow you to track how many times you had called new MyClass() such that there are N instances taking up memory at the moment, and you want to know the value of N?

    If you want to track memory usage, use the debugger to dump the state of the heap. The thing is, the answer will depend on the GC and whether it has collected unreferenced objects.

    You could have a counter you increment in the constructor, but when to decrement it? Finalizers run in another thread, which underlines the unpredictability of this whole idea. Might be better to implement IDisposable to decrement the counter, and require the objects to be Disposed when not needed.

提交回复
热议问题