类子级实现父级:
Child : Parent{}
我可以将子对象添加到父列表中。
List<Parent> var = new List<Parent>();
var.Add(new Child());
但是我该如何将这个Child列表添加到这个字典中呢?
Dictionary<string, List<Parent>> var = new Dictionary<string, List<Parent>>();
var.Add("string", new List<Child>());
嗯,List<Child>
与Child
是完全不同的类型。List<T>
中使用的泛型类型是Child
这一事实无关紧要。Dictionary<string, Child>
包含字符串键和子对象。List<Child>
是孩子吗?不,那怎么办呢?
List<Child>
不能分配给List<Parent>
变量。它们是不相关的类型。这是一个矛盾的"证明"。
假设List<Child>
可以分配给List<Parent>
,那么这将被编译器允许:
List<Parent> parents = new List<Child>();
parents.Add(new Child2()); // Child2 is another subclass of "Parent"
然而,这就产生了矛盾。parents
实际上存储一个List<Child>
,它不能存储Child2
对象。
您可以在此处使用的解决方法是创建一个List<Parent>
对象,并将您的Child
对象添加到该列表中:
var.Add("string", new List<Parent>());
List<Child> children = new List<Child> { ... }
var["string"].AddRange(children);