[英]Keeping Derived Class Properties in a Collection
I am in need of assistance, since I am stuck on a problem I have encountered. 我需要帮助,因为我遇到了遇到的问题。 I have a List ,
List<Items> ItemList
and I want to put some ContainerItems into that list, but when I do, all of the ContainerItems properties are gone and it turns into the baseclass of Items 我有一个List ,
List<Items> ItemList
,我想将一些ContainerItem放入该列表中,但是当我这样做时,所有的ContainerItems属性都消失了,它变成了Items的基类
class Items
{
public Items()
{
}
public string Name { get; set; }
public int durability { get; set; }
}
class ContainerItems : Item
{
public ContainersItem()
{
}
public int maxItems { get; set; }
public List<Items> ContainItems { get; set;}
}
Ideally I would like store all of the Items I'm making into a Dictionary<string,Items>
. 理想情况下,我想将我正在制作的所有项目存储到
Dictionary<string,Items>
。 Is there anyway to store all the Items and ContainerItems together and keep their properties? 有没有将所有Items和ContainerItem存储在一起并保留其属性? thanks in advance!
提前致谢!
Lets say you have your list of Items: 让我们说你有你的物品清单:
public List<Items> ContainItems { get; set }
And now you want to loop through them, but safely as not all of the members of the list will be a ContainerItems
object: 现在你想循环遍历它们,但是安全的并不是列表的所有成员都不是
ContainerItems
对象:
foreach(var item in ContainItems)
{
if(item is ContainerItems)
{
var containerItems = (ContainerItems)item;
}
else
{
//Otherwise deal with it as an Items object
}
}
您将(1)将列表定义为List<ContainersItem>
或(2)每次要使用特定于此类的字段或函数时,在ContainersItem
列表的内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.