您的位置:首页 > 其它

获得托管对象大小

2006-12-11 21:21 267 查看
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace WindowsApplication1
{
public class c
{
int a = 0;
string str = "hell";
string str2 = "hell";
string str3 = "hell";
string str4 = "hell";
string str5 = "hell";
}

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

private void button1_Click(object sender, EventArgs e)
{
c c1 = new c();
MessageBox.Show(Calc(c1).ToString());
}

private static int Calc(object o)
{
FieldInfo[] filist = o.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (filist.Length < 1) return -1;

int ret = 0;

foreach (FieldInfo fi in filist)
{
int len = 0;
int len2 = -1;
try
{
//object o2 = Activator.CreateInstance(fi.GetType());
object o2 = fi.GetValue(o);
Type t2 = o2.GetType();
if (o2 is System.Int32) { len = 4; goto end; }
else if (o2 is System.Byte) { len = 1; goto end; }
else if (o2 is System.Int32[]) { len = ((byte[])o2).Length * 4; goto end; }
else if (o2 is System.Byte[]) { len = ((byte[])o2).Length; goto end; }
else if (o2 is System.String) { len = Convert.ToString(o2).Length; goto end; }
else if (o2 is System.Single) { len = 4; goto end; }
else
{
Console.WriteLine("Below is " + o2.GetType().Name);
len2 = Calc(o2);
Console.WriteLine("end of " + o2.GetType().Name + "(Total) --- " + len2.ToString());
}
end:
ret += len;
if (len2 > -1) ret += len2;
Console.WriteLine(fi.Name + " --- " + len.ToString());
}
catch
{

}
}

return ret;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: