如何在内存中计算类实例大小?

时间:2015-06-17 05:21:26

标签: c# class

如何计算内存中的类实例大小?我想比较两个类实例的大小,它们在ram中的大小。我该怎么办?

void Main()
{
    var foo1 = new Foo();
    foo1.A = 1;
    foo1.B = "A";
    foo1.C = 2;
    foo1.D = "B";

    var foo2 = new Foo();
    foo2.A = 1;
    foo2.B = "AB";
    foo2.C = 2;
    foo2.D = "CD";

    // Get the size of foo1 & foo2 and compare them to each other.
}

class Foo
{
    public int A { get; set; }
    public string B { get; set; }
    public int C { get; set; }
    public string D { get; set; }
}

1 个答案:

答案 0 :(得分:1)

选中此Link

long size = 0;
object o = new object();
using (Stream s = new MemoryStream()) {
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(s, o);
    size = s.Length;
}