代码之家  ›  专栏  ›  技术社区  ›  Mister 832

ObservableCollection类型的属性<UnknownType>

c#
  •  0
  • Mister 832  · 技术社区  · 7 年前

    我想提供一个返回 ObservableCollection ,其中类型是任何模型类。

    internal ObservableCollection<_t> DetailsCollection(Type _t)
    {
        ObservableCollection<_t> col = new ObservableCollection<_t>();
    
        _t obj = (_t)Activator.CreateInstance(_t);
    
        col.Add(obj);
    
        return col;
    }
    

    这样做的原因是,某些模型类具有该类型的属性 ObservableCollection<AnotherModelClass> ,例如,对于主细节实体。我想把这个类的实例传递给一个泛型函数,这个泛型函数用数据库中的值填充属性。

    下面是一些示例代码,可能有助于解释我要做的事情:

        class CustomerModel : ModelBase
    {
        public int Id { get; set; }
    
        public string Name { get; set; }
    
        public ObservableCollection<AddressModel> Addresses { get; set; }
    }
    
    class InvoiceModel : ModelBase
    {
        public int Id { get; set; }
    
        public string Name { get; set; }
    
        public CustomerModel Customer { get; set; }
    
        public ObservableCollection<ItemModel> Items { get; set; }
    }
    
    
    class ItemModel : ModelBase
    {
        public int Id { get; set; }
    
        public string Name { get; set; }
    
        public ObservableCollection<SupplierModel> Suppliers { get; set; }
    }
    
    class ViewModelBase 
    {
    
        public void LoadModelData(ModelBase ent)
        {
            //fill properties with values from the database
            //I got this working for the System types, like Id and Name
            //and for the properties that have a type derrived from ModelBase
            //like the Customer property of Invoice. But it should
            //look sth. like this
    
            foreach (DataRow row in recorddetailstable.Rows)
            {
                DetailModel det = new DetailModel() { Id = row["IdInDb"], Name = row["NameInDb"] };
                ent.property.add(det); 
            }
        }
    }
    

    这能做到吗?

    0 回复  |  直到 7 年前