C# 计算变量大小


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

// Marshal 域名空间
using System.Runtime.InteropServices;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

    
        private void Form1_Load(object sender, EventArgs e)
        {
            

            int num_Size = sizeof(Int32);// 16->2,32->4,64->8
            SetText("Int32 Size sizeof =" + num_Size);
            

            People pp = new People();
           // Marshal.SizeOf用于引用类型,非托管
           var size = Marshal.SizeOf(pp);
           SetText("People sizeof =" + size);

        }

        public void SetText(string txt)
        {
            textBox1.AppendText(txt + "\r\n");
        }
    }

    [StructLayout(LayoutKind.Sequential)] // 必须要加这个,否则不能计算
    public class People
    {        
        public string Name;
        public int Age;
        public string Sex;
    }
}



C# 计算变量大小_第1张图片

推荐博客:

http://www.cnblogs.com/supperwu/archive/2013/05/16/3082061.html










你可能感兴趣的:(C#,开发总结)