【问题标题】:How to calculate a class instance size in memory? [duplicate]如何计算内存中的类实例大小? [复制]
【发布时间】:2015-09-02 04:11:15
【问题描述】:

如何计算内存中的类实例大小?我想比较两个类实例的大小,它们在 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; }
}

【问题讨论】:

    标签: c# class


    【解决方案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;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-07-05
      • 2010-12-12
      • 2013-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      • 2020-11-20
      相关资源
      最近更新 更多