我有一个名为Entity的基类.然后我有两个子类Tag,以及从Entity继承的Property.现在我想拥有存储实体列表的字典.但我无法让它发挥作用.错误地完成了继承吗?
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);
Run Code Online (Sandbox Code Playgroud)
这是一个常见的错误.
A List<Derived>
不会自动从a继承List<Base>
,也不能互换使用.其原因是列表是可变结构,即可以添加,删除和修改元素.
例如,如果我有一个List<Dog>
和一个List<Cat>
列表,并且我能够将它们视为a List<Mammal>
,则可以使用以下代码:
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 (!!?!)
Run Code Online (Sandbox Code Playgroud)
但是,如果您不需要列表,只需要集合(并且您使用C#4或更高版本),则可以将字典定义为Dictionary<string, IEnumerable<Entity>>
.与IEnumerable
它是不可能添加或修改集合,只是列举了,所以任何有趣的经营业务是dissalowed定义.这称为通用类型协方差,如果您想阅读更多有关该主题的内容,有几个很棒的Eric Lippert博客.