伯爵类的实例 [英] Count instances of the class

查看:193
本文介绍了伯爵类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/2392075/how-can-i-find-out-how-many-objects-are-created-of-a-class-in-c-sharp">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);
    }
}

也看看下面类似的问题 - <一个href="http://stackoverflow.com/questions/1168746/c-sharp-count-number-of-objects-of-class-type-within-class-method">Count类类型的类方法中的对象的数量

这篇关于伯爵类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆