首页 > 解决方案 > 将派生类型的集合作为基类型的集合访问

问题描述

我对所有模型类都有一个基本类型,它提供了一些基本属性。一些模型表示主从关系,这些关系存储在 的属性中ObservableCollection<DetailModel>

我想以通用方法访问这些详细信息集合,如下所示。

    public class ModelBase
    {

        public int Id { get; set; }

        public string Description { get; set; }

    }

    public class DaugtherModel : ModelBase
    {

    }

    public class SonModel : ModelBase
    {

    }


    public class MotherModel : ModelBase
    {
        public ObservableCollection<DaugtherModel> Daughters { get; set; } = new ObservableCollection<DaugtherModel>();

        public ObservableCollection<SonModel> Sons { get; set; } = new ObservableCollection<SonModel>();

    }

    class Program
    {
        static void Main(string[] args)
        {


            MotherModel mother = new MotherModel();

            PropertyInfo[] infos = mother.GetType().GetProperties();

            foreach (PropertyInfo motherProp in infos.Where(x => x.PropertyType.Namespace == "System.Collections.ObjectModel").ToList())
            {
                // Here I get an error Unable to cast object of type 'System.Collections.ObjectModel.ObservableCollection`1[vererbung.DaugtherModel]' to type 'System.Collections.ObjectModel.ObservableCollection`1[vererbung.ModelBase]'
                foreach (ModelBase child in (ObservableCollection<ModelBase>)motherProp.GetValue(mother))
                {
                    Console.WriteLine(child.Description);
                }
            }
        }
    }

代码抛出以下错误消息:

无法转换类型的对象

'System.Collections.ObjectModel.ObservableCollection'1[vererbung.DaugtherModel]' 输入'System.Collections.ObjectModel.ObservableCollection'1[vererbung.ModelBase]'

如何通过基类型访问 cild 对象?

标签: c#inheritance

解决方案


您不需要在列表的 foreach 中使用您的演员表,followig 会做:

foreach (ModelBase child in MotherProp.GetValue(mother))

推荐阅读