简体   繁体   中英

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

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> . Is there anyway to store all the Items and ContainerItems together and keep their properties? 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:

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列表的内容

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM