【发布时间】:2010-08-11 12:07:14
【问题描述】:
在 C# 中,我有一堆对象都继承自同一个基类。
我还有许多字典,每个子类一个。
我想要做的是将所有这些字典添加到一个 List 中,这样我就可以遍历它们并做一些工作(比如比较列表等)。
总结
Dictionary<string, Child> childObjects = new Dictionary<string, Child>();
List<Dictionary<string, Parent>> listOfDictionaries = new List<Dictionary<string, Parent>>();
listOfDictionaries.Add(childObjects);
我会认为既然 Child 继承自 Parent,这应该可以工作,但它不会编译。显然我对继承和泛型不了解:)
完整的代码示例
class Program
{
static void Main(string[] args)
{
//Creating a Dictionary with a child object in it
Dictionary<string, Child> childObjects = new Dictionary<string, Child>();
var child = new Child();
childObjects.Add(child.id, child);
//Creating a "parent" Dictionary with a parent and a child object in it
Dictionary<string, Parent> parentObjects = new Dictionary<string, Parent>();
parentObjects.Add(child.id, child);
var parent = new Parent();
parentObjects.Add(parent.id, parent);
//Adding both dictionaries to a general list
List<Dictionary<string, Parent>> listOfDictionaries = new List<Dictionary<string, Parent>>();
listOfDictionaries.Add(childObjects); //This line won't compile
listOfDictionaries.Add(parentObjects);
}
}
class Parent
{
public string id { get; set; }
public Parent()
{
this.id = "1";
}
}
class Child : Parent
{
public Child()
{
this.id = "2";
}
}
有什么方法可以实现吗?
【问题讨论】:
标签: c# generics inheritance