1

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

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

我的问题是无论如何移动标记包含列表可以包含的所有可能类型的 Type[] 的位置?我想将以下内容添加到我的 CustomCollectionEditor 类中,但这不起作用。

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

如果我能以某种方式在 DisplayList 类中标记 CustomCollectionEditor 需要注意的类,那将是理想的。

4

1 回答 1

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;
  }
于 2010-03-26T07:27:18.723 回答