dimanche 27 janvier 2019

How to quickly search for objects of certain class or child classes in C#

I want to make a collection of objects of various classes, and be able to quickly search for all instances that can be assigned to a specific class, without having to iterate the entire list. I can use a Dictionary<System.Type, List<object>>, however that won't find me all child classes.

public class Parent {
}

public class Child : Parent {
}

public class Other {
}


public class ObjHolder {
    Dictionary<System.Type, List<object>> objs = new Dictionary<System.Type, List<object>>();

    public void AddObject(object obj) {
        if (!objs.ContainsKey(obj.GetType()) {
            objs[obj.GetType()] = new List<object>();
        }

        objs[obj.GetType()] = obj;
    }

    public List<object> GetObjectsOfType<T>() {
        return objs.ContainsKey(typeof(T)) ? objs[typeof(T)] : new List<object>();
    }
}

Now this will work great for the following:

ObjHolder o = new ObjHolder();
o.AddObject(new Parent());
o.AddObject(new Other());
o.GetObjectsOfType<Parent>(); // Returns only the Parent object    

But this won't work in the following case:

ObjHolder o = new ObjHolder();
o.AddObject(new Child());
o.AddObject(new Other());
o.GetObjectsOfType<Parent>(); // Returns an empty list

I want to be able to grab all objects that can be assigned to Parent, and that include the Child object, but the code won't return it.

Any ideas how to get this done in an efficient matter?





Aucun commentaire:

Enregistrer un commentaire