计算类的实例 [英] Count instances of the class
问题描述
是否可以获取所选类的活动(已创建但尚未销毁)的实例数? / p>
例如
public class MyClass
{
}
c1 = new MyClass();
c2 = new MyClass();
count = GetActiveInstances(typeof(MyClass))
如果GC销毁任何这些类然后1或0。
您可以在程序中保存全局静态计数器。
这是一个简单的线程安全解决方案:
class MyClass
{
static int counter = 0;
public MyClass()
{
Interlocked.Increment(ref counter);
}
〜MyClass()
{
Interlocked.Decrement(ref counter);
}
}
也看看下面的类似问题 - a href =http://stackoverflow.com/questions/1168746/c-sharp-count-number-of-objects-of-class-type-within-class-method>在类中计算类类型的对象数方法
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?
For example
public class MyClass
{
}
c1 = new MyClass();
c2 = new MyClass();
count = GetActiveInstances(typeof(MyClass))
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);
}
~MyClass()
{
Interlocked.Decrement(ref counter);
}
}
also take a look at the following similar question - Count number of objects of class type within class method
这篇关于计算类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!