我怎么能找出多少对象在C#中创建一个类 [英] how can i find out how many objects are created of a class in C#

查看:113
本文介绍了我怎么能找出多少对象在C#中创建一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能找出多少对象在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);
    }
}

一对夫妇的注意事项:

A couple of notes:


  • 这不算数的当前内存的实例的数量 - 这将涉及到有一个终结递减计数器;我不建议

  • 这将不包括通过一些机制如序列化可以绕过一个构造函数创建的实例

  • 显然,这只是工作,如果你可以修改类;你无法找到的实例数 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?

这篇关于我怎么能找出多少对象在C#中创建一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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