2010-03-05 36 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; 
    } 
相關問題