C# 如何将子类字典视为基类字典
在C#中,我有一堆对象,它们都继承自同一基类。C# 如何将子类字典视为基类字典,c#,generics,inheritance,C#,Generics,Inheritance,在C#中,我有一堆对象,它们都继承自同一基类。 我还有很多字典,每个子类一本。 我想做的是将所有这些词典添加到一个列表中,这样我就可以循环浏览它们并做一些工作(比如比较列表等) 总之 Dictionary<string, Child> childObjects = new Dictionary<string, Child>(); List<Dictionary<string, Parent>> listOfDictionaries = new Li
我还有很多字典,每个子类一本。
我想做的是将所有这些词典添加到一个列表中,这样我就可以循环浏览它们并做一些工作(比如比较列表等) 总之
Dictionary<string, Child> childObjects = new Dictionary<string, Child>();
List<Dictionary<string, Parent>> listOfDictionaries = new List<Dictionary<string, Parent>>();
listOfDictionaries.Add(childObjects);
Dictionary childObjects=new Dictionary();
List listOfDictionaries=新列表();
添加(子对象);
我本以为既然子对象继承自父对象,这应该可以工作,但它不会编译。显然,我对继承和泛型还不太了解:)
完整的代码示例
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";
}
}
类程序
{
静态void Main(字符串[]参数)
{
//创建包含子对象的词典
Dictionary childObjects=新字典();
var child=new child();
添加(child.id,child);
//创建包含父对象和子对象的“父”词典
Dictionary parentObjects=new Dictionary();
parentObjects.Add(child.id,child);
var parent=新父级();
parentObjects.Add(parent.id,parent);
//将两个词典添加到常规列表
List listOfDictionaries=新列表();
添加(childObjects);//此行无法编译
添加(父对象);
}
}
班级家长
{
公共字符串id{get;set;}
公共家长()
{
此参数为“.id=”1”;
}
}
类子:父
{
公共儿童()
{
此参数为1.id=“2”;
}
}
有什么办法可以做到这一点吗?你不能安全地做到这一点。想象你这样做:
listOfDictionaries[0]["foo"] = new Parent();
这看起来不错,但这意味着childObjects
将包含一个不是Child
实例的值
C#4在安全的情况下引入了受限的通用方差-例如,您可以将类型为IEnumerable
的引用转换为IEnumerable
的引用-但是您想要在这里执行的操作并不安全,因此仍然是不允许的
如果你能告诉我们更多关于更大背景的信息——你正在努力实现的目标——我们也许能提供更多帮助。你能举例说明你以后想对列表做些什么吗?谢谢Jon,他没有考虑过更新。上下文是比较两组元数据的比较工具。所以,我有一个字典列表,里面有东西,我只需要能够比较它们,看看它们是否包含相同的对象。compare函数是在基类上定义的,因此根据您的建议,我将只使用Parent[]t=childObjects.Values.ToArray();我可以循环遍历数组或将其转换回字典。不是很漂亮,但是足够好了。谢谢