c# - 将派生类型的集合作为基类型的集合访问
问题描述
我对所有模型类都有一个基本类型,它提供了一些基本属性。一些模型表示主从关系,这些关系存储在 的属性中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 对象?
解决方案
您不需要在列表的 foreach 中使用您的演员表,followig 会做:
foreach (ModelBase child in MotherProp.GetValue(mother))
推荐阅读
- java - 我们可以使用 Selenium 或任何其他 jar 来获得网络响应和验证吗
- c - 使用管道在父子之间进行通信
- python - 为什么调用函数会导致 NameError?
- google-apps-script - 如何每天午夜自动删除 Google 表格中定义的行?
- html - 如何在按钮内移动图像?
- sql - 在 PL/SQL 中不使用 For 循环来计算公式的函数
- csv - Nifi:检查 CSV 文件的行更新,然后摄取
- javascript - 从 OSM 服务器地图导出 SVG
- javascript - 如何将字符串附加到 Vue 模板中的常量?
- python - 解析Python目录中的所有XML文件