I have a base type for all model classes, which provides some basic properties. Some models represent master detail relations, which are stored in property of ObservableCollection<DetailModel>
.
I want to access theses detail collections in a generic approach, as shown below.
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);
}
}
}
}
The code throws the following error message:
Unable to cast object of type
'System.Collections.ObjectModel.ObservableCollection'1[vererbung.DaugtherModel]' to type 'System.Collections.ObjectModel.ObservableCollection'1[vererbung.ModelBase]'
How can access the cild objects through the base type?