本文介绍了我如何找出一个类创建了多少个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何找出在C#中为一个类创建了多少个对象?
How can I find out how many objects are created of a class in C#?
推荐答案
您必须放入一个静态计数器,该计数器在构造上递增:
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);
}
}
一些注意事项:
- 这不计算当前正在存储的实例的数量-这需要使用终结器来减少计数器;我不建议
- 这不包括通过某些机制(例如序列化)创建的实例,这些机制可能会绕过构造函数
- 显然,这仅在以下情况下有效您可以修改课程;例如,您无法找出所创建的
System.String
的实例数量-至少在没有不插入调试/概要分析API的情况下,
- 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?
这篇关于我如何找出一个类创建了多少个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!