首页 > 解决方案 > 在这种情况下,如何通过将对象添加到字典来实现多态性?

问题描述

子类实现父类:

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>());

标签: c#listdictionarypolymorphism

解决方案


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);

推荐阅读