简体   繁体   English

将父类型的 ObservableCollection 转换为子类型

[英]Convert ObservableCollection of parent type to child

I have class CheckBoxObject and DeployCheckBoxObject that derived from CheckBoxObject.我有 class CheckBoxObject 和从 CheckBoxObject 派生的 DeployCheckBoxObject。

i have observable collection of CheckBoxObject and for each element of the collection want to use child properties and functions.我有 CheckBoxObject 的可观察集合,并且集合中的每个元素都想使用子属性和函数。

how can i convert the parent collection to child?如何将父集合转换为子集合?

public class CheckboxObject : ViewModelBase
{
        public CheckboxObject(object o)
        {
            Object = o;
        }
        public object Object;
        public string Name => Object.ToString();
}

public class DeployCheckBoxObject : CheckboxObject
{
        public DeployCheckBoxObject(object o) : base(o)
        {

        }
        
        public string status { get; set; }
}

public class Test
{
        ObservableCollection<DeployCheckBoxObject> items = new ObservableCollection<DeployCheckBoxObject>();

public void populate(someObject) {

  items = someObject.ToObservableCheckboxCollection(); //error

  }

}

I also try to call child functions with parent object and get invalid cast error我也尝试用父 object 调用子函数并得到无效的转换错误

public class Test
{
        ObservableCollection<CheckBoxObject> items = new ObservableCollection<CheckBoxObject>();

  public void populate(someObject) {

   items = someObject.ToObservableCheckboxCollection(); 
   foreach (CheckboxObject cb in CbVendorItems) {
     ((DeployCheckBoxObject)cb).Count = 100; //error
   }
  }

}
public static ObservableCollection<CheckboxObject> ToObservableCheckboxCollection<T>(this IEnumerable<T> enumerableList)
        {
            var a = new ObservableCollection<CheckboxObject>();
            if (enumerableList == null) return a;
            foreach (var item in enumerableList)
            {
                a.Add(new CheckboxObject(item));
            }
            return a;
        }

how can i access to child methods?我怎样才能访问子方法?

Do you know that all the CheckBoxObject s in your collection are actually DeployCheckBoxObject s, if so, then why not make your observable collection of the type DeployCheckBoxObject instead of CheckBoxObject您是否知道您集合中的所有CheckBoxObject实际上都是DeployCheckBoxObject ,如果是这样,那么为什么不将您的可观察集合DeployCheckBoxObject而不是CheckBoxObject

If you don't know for sure, and some CheckBoxObject s may not be a DeployCheckBoxObject then you need to check for type safety before casting如果您不确定,并且某些CheckBoxObject可能不是DeployCheckBoxObject那么您需要在转换之前检查类型安全

foreach (CheckboxObject cb in CbVendorItems)
{
    if (cb is DeployCheckBoxObject deployCb)
    {
        deployCb.Count = 100;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM