0

I have the following class.

class MyClass<T>
{
    private static List<T> _Values;
    public static List<T> Values
    {
        get { return (_Values = _Values ?? new List<T>()); }
    }
}

I have used it several times like this.

MyClass<Int32>.Values.Add(1);
MyClass<String>.Values.Add("1");

Is there any possibility to retrieve all Lists of all types that have ever been used and are in the memory now using reflection?

Something like

var lists = typeof(MyClass<>)
    .MemoryOccurrences()
    .Select(x => x.GetStaticVariable("Values")); // two lists expected in this case
Oybek
  • 7,016
  • 5
  • 29
  • 49

1 Answers1

1

You can't do it with Reflection, but you can do it create a instance holder, like this

public class MyClassInstanceHolder
{
    private static Dictionary<Type, object> Instances { get; } = new Dictionary<Type, object>();

    public static List<T> GetNewOrExistent<T>()
    {
        var type = typeof(MyClass<T>);
        if (Instances.ContainsKey(type))
            return (List<T>)Instances[type];

        Instances.Add(type, MyClass<T>.Values);
        return MyClass<T>.Values;
    }

    public static IEnumerable<object> GetAllInstances() => Instances.Select(i => i.Value);
}

Then you can still use it with a small change

MyClassInstanceHolder.GetNewOrExistent<int>().Add(1);
MyClassInstanceHolder.GetNewOrExistent<int>().Add(2);
MyClassInstanceHolder.GetNewOrExistent<int>().Add(3);
MyClassInstanceHolder.GetNewOrExistent<string>().Add("string value");

And you can all get all instances values.

foreach (var allInstance in MyClassInstanceHolder.GetAllInstances())
{
    foreach (var o in (IEnumerable) allInstance)
        Console.WriteLine(o);
    Console.WriteLine("=================");
}

1

2

3

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

string value

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

Alberto Monteiro
  • 5,989
  • 2
  • 28
  • 40