C#结构体大小如何计算?结构体中有个数不确定的List

2025-01-31 02:04:50
推荐回答(1个)
回答1:

计算这些结构体时,注意以下几点:

1)结构体成员如果类实例、数组,则其在结构体中保存的引用。

  • 在32位模式下,每个引用占用4个字节(32位);

  • 在64位模式下,每个引用占用8个字节(64位)

2)标准数据类型

  • short/ushort:2字节

  • int/int32/uint:4字节

  • DateTime: 8字节

============

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

namespace ConsoleSizeOf
{
        [StructLayout (LayoutKind.Sequential,Pack =1)]
        struct ScheduleFile
        {
            public Int32 schedule_id;
            public byte[] basic_schedule_name;  
            public Int32 table_count;//服务个数(表个数)
            public Table []table_list;//服务列表
            DateTime t;
        }
        //结构体Table
        [StructLayout(LayoutKind.Sequential,Pack =1)]
        struct Table
        {
            public Int32 table_id;
            public Int32 trip_cnt;
            public Trip []trip_list;
        }
        //结构体Trip
        [StructLayout(LayoutKind.Sequential,Pack =1)]
        struct Trip//单程
        {
            public byte[] local_sub_id;
            public byte[] global_sub_id;
            public ushort trip_flag;
            public ushort route_id;
            public ushort loop_id;
            public byte[] destination_code;
            public ushort record_cnt;
            public Record []record_list;
        }
        //结构体Record
        [StructLayout(LayoutKind.Sequential,Pack =1)]
        struct Record//记录
        {
            public ushort station_id;
            public ushort platform_id;
            public DateTime arrival_time;
            public DateTime departure_time;
            public Int32 performance_level;
            public ushort record_flag;
        }

    class Program
    {
        static void Main(string[] args)
        {
            ScheduleFile sf = new ScheduleFile();
            Console.WriteLine("SizeOf(ScheduleFile)={0}", Marshal.SizeOf(sf));
            sf.basic_schedule_name = new byte[100];
            Console.WriteLine("SizeOf(ScheduleFile)={0}, 数组basic_schedule_name已赋值!",
                 Marshal.SizeOf(sf));
            sf.table_list = new Table[100];
            Console.WriteLine("SizeOf(ScheduleFile)={0}, 数组table_list已赋值!", 
                Marshal.SizeOf(sf));

            Table tb = new Table();
            Console.WriteLine("SizeOf(Table)={0}", Marshal.SizeOf(tb));

            Trip tp = new Trip();
            Console.WriteLine("SizeOf(Trip)={0}", Marshal.SizeOf(tp));

            Record rc = new Record();
            Console.WriteLine("SizeOf(Trip)={0}", Marshal.SizeOf(rc));
        }
    }
}

以下结果是在64位系统运行的结果

注意红色方框中的计算结果!