c# - 在这种情况下,如何通过将对象添加到字典来实现多态性?
问题描述
子类实现父类:
Child : Parent{}
我可以将子对象添加到父列表。
List<Parent> var = new List<Parent>();
var.Add(new Child());
但是我怎样才能将这个 Child 列表添加到这个 Dictionary 中呢?
Dictionary<string, List<Parent>> var = new Dictionary<string, List<Parent>>();
var.Add("string", new List<Child>());
解决方案
AList<Child>
不能分配给List<Parent>
变量。它们是不相关的类型。这是一个矛盾的“证明”。
假设List<Child>
可以分配给List<Parent>
,那么编译器将允许这样做:
List<Parent> parents = new List<Child>();
parents.Add(new Child2()); // Child2 is another subclass of "Parent"
然而,这会产生矛盾。parents
实际上存储 a List<Child>
,它不能存储Child2
对象。
您可以在此处使用的解决方法是创建一个List<Parent>
对象,并将您的Child
对象添加到该列表中:
var.Add("string", new List<Parent>());
List<Child> children = new List<Child> { ... }
var["string"].AddRange(children);
推荐阅读
- c# - 如果不存在,MongoDB 添加新的对象数组字段
- javascript - 如何在反应钩子中修复部门上的显示列表
- docker - 如何使用 Bamboo 从经过身份验证的注册表中将 Docker 映像提取到 ECR 中的特定存储库?
- kubernetes - 无法通过主节点 IP 访问在工作节点上运行的 Kubernetes pod
- java - 无法启动tomcat(org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading非法访问:)
- python - python多处理管理器连接创建另一个对象
- powershell - Powershell:写入单个日志文件
- java - pkcs#10 请求的格式,EJBCA
- angular - Angular 7:TypeError:构建生产代码时无法读取未定义的属性“种类”
- aem - 如何将 favicon 添加到 AEM 资产,例如 pdf/视频