类型ObservableCollection <UnknownType>的属性

时间:2019-06-20 18:14:28

标签: c#

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

internal ObservableCollection<_t> DetailsCollection(Type _t)
{
    ObservableCollection<_t> col = new ObservableCollection<_t>();

    _t obj = (_t)Activator.CreateInstance(_t);

    col.Add(obj);

    return col;
}

之所以这样做,是因为某些Model类的属性类型为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 个答案:

没有答案