伯爵类的实例伯爵、实例

2023-09-03 12:44:20 作者:猛|風|勁|走|

可能重复:   how我可以找出多少个对象在C#中创建了一个类的

Possible Duplicate: how can i find out how many objects are created of a class in C#

时有可能得到情况是积极的(创建,尚未销毁)选定类的数量?

Is it possible to get number of instances which is active(created and not yet destroyed) for selected class?

例如

public class MyClass
{
}

    c1 = new MyClass();
    c2 = new MyClass();

    count = GetActiveInstances(typeof(MyClass))

应该返回2.如果GC破坏任何这些类的话1或0。

should return 2. If GC destroy any of these classes then 1 or 0.

推荐答案

您可以拥有你的程序全局静态计数器。 这是一个简单的线程安全的解决方案:

You can holds global static counter in your program. This is a simple thread safe solution:

class MyClass
{
    static int counter = 0;

    public MyClass()
    {
        Interlocked.Increment(ref counter);
    }

    public ~MyClass()
    {
        Interlocked.Decrement(ref counter);
    }
}

也看看下面类似的问题 - Count类类型的类方法中的对象的数量

 
精彩推荐
图片推荐