如何找出一个类创建了多少个对象 [英] How can I find out how many objects are created of a class
本文介绍了如何找出一个类创建了多少个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 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?
这篇关于如何找出一个类创建了多少个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文