Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

c# - How can I find out how many objects are created of a class

How can I find out how many objects are created of a class in C#?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'd have to put a static counter in that was incremented on construction:

public class Foo
{
    private static long instanceCount;

    public Foo()
    {
        // Increment in atomic and thread-safe manner
        Interlocked.Increment(ref instanceCount);
    }
}

A couple of notes:

  • This doesn't count the number of currently in memory instances - that would involve having a finalizer to decrement the counter; I wouldn't recommend that
  • This won't include instances created via some mechanisms like serialization which may bypass a constructor
  • Obviously this only works if you can modify the class; you can't find out the number of instances of System.String created, for example - at least not without hooking into the debugging/profiling API

Why do you want this information, out of interest?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...