在C中,有许多对象都继承自同一个基类。
我还有许多字典,每个子类一个。
我要做的是把所有的字典都加在一本上
表
所以我可以循环浏览它们并做一些工作(比如比较列表等)。
综上所述
Dictionary<string, Child> childObjects = new Dictionary<string, Child>();
List<Dictionary<string, Parent>> listOfDictionaries = new List<Dictionary<string, Parent>>();
listOfDictionaries.Add(childObjects);
我本以为既然孩子是从父母那里继承的,这应该是可行的,但它不会编译。很明显,我对继承和仿制药不了解。)
完整的代码示例
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";
}
}
有什么办法可以达到这个目的吗?