سؤال

Solved.

I was wondering if anyone knows if it's possible to get all instantiated types of a specific type during runtime?

Let's say I want to Enumerate all instantiated objects of the type Foo.

public class Foo {}

var foo1 = new Foo();
Foo foo2 = new Foo();

IEnumerable<Foo> foos = GetObjects<Foo>(); 
//foos should contain foo1 and foo2

If there isn't a straight forward way of doing this, then I could just make a base type that subscribes its self on construction to some static service, and then do the look up that way... But I feel like this must already be implemented for the GC to work.


I would give most of you correct answer if I could, but since I couldn't I gave it to the first person to answer.

هل كانت مفيدة؟

المحلول 2

Answered over on the MSDN forums: http://social.msdn.microsoft.com/Forums/vstudio/en-US/f9e984e3-a47b-42b0-b9bd-1f1c55e4de96/getting-all-running-instances-of-a-specific-class-type-using-reflection?forum=netfxbcl

Not possible :(

Though they at least give you an idea of creating a static List to hold all references of the type (provided its your type of course) that you add to at creation time.

نصائح أخرى

I'm afraid there is nothing like that available within the framework.

You would have to keep track of constructed instances by your own, e.g. using internal list.

public class Foo
{
    private static List<Foo> _instances = new List<Foo>();

    public Foo()
    {
        _instances.Add(this);
    }

    public static IEnumerable<Foo> Instances { get { return _instances; } }
}

You could use WeakReference to allow GC collect these instances anyway when no other reference is kept.

public class Foo
{
    private static List<WeakReference<Foo>> _instances = new List<WeakReference<Foo>>();
    public Foo()
    {
        _instances.Add(new WeakReference<Foo>(this));
    }

    public static IEnumerable<Foo> Instances
    {
        get
        {
            foreach(var r in _instances)
            {
                Foo instance;
                if (r.TryGetTarget(out instance))
                    yield return instance;
            }
        }
    }
}

In this case if there is no issue with memory consumption you could also use local static collection of same class instance. This way in constructor you can add each new instance to this collection.

Then in case whenever you want to know all instances you can get it from this local static collection like below...

class Foo
{
   public static List<Foo> Instances = new List<Foo>();
   public Foo()
   {
     Instances.Add(this);
   }
  //can be accessed like below
   Foo.Instances
 }

This might help to solve your problem.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top