如何在字典中存储基层儿童? [英] How to store base class children in a dictionary?

查看:48
本文介绍了如何在字典中存储基层儿童?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个称为Entity的基类. 然后,我有两个子类Tag,以及从Entity继承的Property. 现在,我想拥有存储实体列表的字典.但是我无法使它正常工作.继承做错了吗?

I have base class that is called Entity. Then I have two child class Tag, and Property that inherits from Entity. Now I want to have dictionary that stores a List of Entity. But I cannot get it to work. Have a done the inheritance wrongly?

Dictionary<string, List<Entity>> baseDict = new Dictionary<string, List<Entity>>();

List<Tag> tags = new List<Tag>();
tags.Add(new Tag("2012"));
tags.Add(new Tag("hello"));
tags.Add(new Tag("lego"));
List<Properties> properties = new List<Properties>();
properties.Add(new Properties("Year"));
properties.Add(new Properties("Phrase"));
properties.Add(new Properties("Type"));

baseDict.Add("Tags", tags);
baseDict.Add("Properties", properties);

推荐答案

这是一个常见错误.

List<Derived>不会自动从List<Base>继承,并且它们不能互换使用.这样做的原因是列表是可变的结构,即可以添加,删除和修改元素.
例如,如果我有一个List<Dog>List<Cat>列表,并且能够将它们视为List<Mammal>,那么以下代码将是可能的:

A List<Derived> does not automatically inherit from a List<Base>, and they cannot be used interchangeably. The reason for this is that a list is a mutable structure, i.e. elements can be added, removed, and modified.
For example, if I have a List<Dog> and a List<Cat> lists, and I was able to treat them as a List<Mammal>, then the following code will be possible:

List<Dog> dogs = new List<Dog>();  //create a list of dogs
List<Mammal> mammals = dogs;   //reference it as a list of mammals
List<Cats> cats = mammals;  // reference the mammals as a list of cats (!!?!)
Cat tabby = new Cat();
mammals.Add(tabby)   // adds a cat to a list of dogs (!!?!)

但是,如果您不需要列表,而只需要集合(并且使用C#4或更高版本),则可以将字典定义为Dictionary<string, IEnumerable<Entity>>.在IEnumerable中,不可能添加或修改集合,而只能枚举它,因此根据定义,将拒绝任何有趣的业务.这称为通用类型协方差,如果您想了解更多信息,关于这个主题,有几个很棒的Eric Lippert博客

However, if you do not need lists, just collections, (and you use C# 4 or later), you could define the dictionary as Dictionary<string, IEnumerable<Entity>>. WIth an IEnumerable it is not possible to add or modify the collection, just enumerate it, so any funny bussiness is by definition dissalowed. This is called Generic Type Covariance, and if you would like to read more on the subject, there are several great Eric Lippert blogs.

这篇关于如何在字典中存储基层儿童?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆