views:

127

answers:

1

I currently have a list containing Call's, which is the base class. If I want to add derived classes of Call to the list, I know to do the following.

   public class CustomCollectionEditor : System.ComponentModel.Design.CollectionEditor
    {
      private Type[] types;
      public CustomCollectionEditor(Type type)
        : base(type)
      {
        types = new Type[] { typeof(Call), typeof(CappedCall) };
      }

  protected override Type[] CreateNewItemTypes()
  {
    return types;
  }
}

public class DisplayList
{
  public DisplayList() { }
  [Editor(typeof(CustomCollectionEditor), typeof(UITypeEditor))]
  [DataMember] public List<Call> ListCalls { get; set; }
}

My questions is there anyway of moving where you mark up the Type[] containing all possible types the list can contain? I thought of adding the following to my CustomCollectionEditor class, but this doesn't work.

public CustomCollectionEditor(Type type, List<Type> types_)
  : base(type)
{
  types = types_.ToArray();
}

It would be ideal if I could mark up which classes the CustomCollectionEditor needed to be aware of in the DisplayList class somehow.

A: 

Sure, you can get all types by using reflection.

private Type[] types;
private Type itemType;

public CustomCollectionEditor(Type type) {
   itemType = t.GetProperty("Item").PropertyType;
   types = GetTypes();
}

private Type[] GetTypes() {
            List<Type> tList = new List<Type>();
            Assembly[] appAssemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly a in appAssemblies) {
                Module[] mod = a.GetModules();
                foreach (Module m in mod) {
                    Type[] types = m.GetTypes();
                    foreach (Type t in types) {
                        try {
                            if (/*t.Namespace == "Mynamespace.tofilter" && */!t.IsAbstract) {
                                /* Here you should find a better way to cover all Basetypes in the inheritance tree */
                                if (t.BaseType == itemType || t.BaseType.BaseType == itemType) { 
                                    tList.Add(t);
                                }
                            }
                        }
                        catch (NullReferenceException) { }
                    }
                }
            }
            return tList.ToArray();
        }


  protected override Type[] CreateNewItemTypes()
  {
    return types;
  }
chriszero