2010-03-05 76 views
1

我目前有一个包含Call的列表,它是基类。如果我想将派生类的Call添加到列表中,我知道要执行以下操作。在PropertyGrid中修改CollectionEditor

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; } 
} 

我的问题是否有移动的地方你标记类型[]包含列表可以包含的所有可能的类型?我想将以下内容添加到我的CustomCollectionEditor类中,但这不起作用。

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

这将是理想的,如果我可以标记哪些类CustomCollectionEditor需要注意的DisplayList中类莫名其妙。

回答

1

当然,你可以通过使用反射来获得所有类型。

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; 
    }