回 帖 发 新 帖 刷新版面

主题:如何计算自定义类类型的大小?

class A
{
private int a;
private double b;
}

如何能像C++那样计算类A的大小(字节),用Sizeof(A)出错,请问应该怎么做?

回复列表 (共5个回复)

沙发

引用类型由于其复杂性,不能用sizeof获取大小
大小基本上由运行时决定~~

板凳

如果实在想获取,有没有其他偏门的方法呢?

3 楼

Marshal.SizeOf(typeof(A));

4 楼

运行时错误,不知道怎么解决~~~~~

下面是我的程序:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace Test
{

    class A
    {
        private int a;
        private double b;
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Marshal.SizeOf(typeof(A)));
            
        }
    }
}



未处理的异常:  System.ArgumentException: 类型“类类型.A”不能作为非托管结构进行封送处理;无法计算有意义的大小或偏移量。
   在 System.Runtime.InteropServices.Marshal.SizeOf(Type t)

5 楼

不好意思,我弄错了
Marshal.SizeOf(typeof(A));
这个好像只能对struct有效

我来回复

您尚未登录,请登录后再回复。点此登录或注册