可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
This question already has answers here:
Closed 7 years ago.
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 { }
...
var c1 = new MyClass();
var c2 = new MyClass();
count = GetActiveInstances(typeof(MyClass))
Should return 2. If GC destroy any of these classes then 1 or 0.
回答1:
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
回答2:
this :
public class MyClass
{
private static int instances = 0;
public MyClass()
{
instances++;
}
~MyClass()
{
instances--;
}
public static int GetActiveInstances()
{
return instances;
}
}
use :
MyClass c1 = new MyClass();
MyClass c2 = new MyClass();
int count = MyClass.GetActiveInstances();
回答3:
Only if you implement a counting mechanism inside the constructor (increment) and finalizer (decrement). But even that will not account for instances which are really inactive (noone has any reference to them) but have not been collected yet.
Moreover, adding a finalizer to a class -- no matter how trivial -- will adversely affect performance, which is an argument against doing so.
回答4:
Try this one:
public class MyClass
{
public static int activeCount = 0;
public MyClass() => activeCount++;
~MyClass() => activeCount--;
}
//In the main
var testClass1 = new MyClass();
var testClass2 = new MyClass();
Console.WriteLine(MyClass.activeCount);
回答5:
public class MyClass
{
private static int count;
private static object _lock = new object();
public MyClass()
{
lock(_lock)
{
count++;
}
}
private ~MyClass()
{
lock(_lock)
{
count--;
}
}
}
回答6:
public class MyClass
{
public static int countinstance =0;
MyClass(){ countinstance ++;}
~ MyClass() {countinstance --; }
}
simple and easy get instance active by countinstance
回答7:
Such thing is not possible but you can do something like
Note : ClassInstance
can be also int value just to maintain count.
public class MyType
{
public static List<MyType> ClassInstance = new List<MyType>();
public MyType() => ClassInstance.Add(this);
public RemoveClass(MyType t)
{
ClassInstance.Remove(t);
t = null;
}
public int ActiveCount => ClassInstance.Count;
}
回答8:
I don't know of a built in mechanism, but you can always incrase a private static variable in constructor.
public class MyClass
{
private static int instances = 0;
public MyClass() => instances++;
~MyClass() => instances--;
}
Haven't tried but should work.
回答9:
You can try it by making a static variable for count in class and increment it in constructor
and decrement in destructor
.May this helps you.