Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何检查在c中为一个类型创建了多少实例?_C#_Oop - Fatal编程技术网

C# 如何检查在c中为一个类型创建了多少实例?

C# 如何检查在c中为一个类型创建了多少实例?,c#,oop,C#,Oop,如何检查为特定类型创建的实例数量以及每个实例占用的内存量。请举例说明 根据评论中的建议,我将添加一个示例 public class Myclass { private static long Count; public Myclass() { Interlocked.Increment(ref Count); } } 这只适用于您自己的类,这样您就无法找到System.String的实例数 要了解类的大小,应使用System.Runtime.

如何检查为特定类型创建的实例数量以及每个实例占用的内存量。请举例说明

根据评论中的建议,我将添加一个示例

public class Myclass
{
    private static long Count;

    public Myclass()
    {
         Interlocked.Increment(ref Count);
    }
}
这只适用于您自己的类,这样您就无法找到System.String的实例数

要了解类的大小,应使用System.Runtime.InteropServices;

以及:


以编程方式?这是您创建的类吗?计算任何类的实例数的最佳方法是在类中保留一个静态int计数器,并在构造函数中将其递增1,在dispose方法中将其递减1。确保IDisposable接口已实现谢谢我尝试过它这对我有帮助!!
[StructLayout(LayoutKind.Sequential)]
public class MyClass
{
    public int MyField;
    public int MyField;
}
 int sizeInBytes = Marshal.SizeOf(typeof(MyClass)); //return 8