Skip to content

Instantly share code, notes, and snippets.

@coolya
Created Sep 4, 2012
Embed
What would you like to do?
Objectgraph
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var ref1 = new MeteredReference("hello world");
var list = new List<string> {"foo", "bar", "foobar"};
var ref2 = new MeteredReference(list);
GC.Collect();
Console.WriteLine(ref1.Size);
Console.WriteLine(ref2.Size);
list.Clear();
GC.Collect();
Console.WriteLine(ref2.Size);
Console.ReadKey();
}
class MeteredReference
{
static Type s_type = Type.GetType("System.SizedReference", true, false);
public MeteredReference(object target)
{
_sizedRef = Activator.CreateInstance(s_type, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, new object[]
{
target
}, null);
}
public long Size
{
get
{
return (long)s_type.InvokeMember("ApproximateSize", BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty, null, _sizedRef, null, CultureInfo.InvariantCulture);
}
}
public object _sizedRef;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment