我有这样的东西:
public class Item
{
public int itemID;
public string itemName;
}
public class Tool : Item
{
public int toolDurability;
}我想创建一个Dictionary,比如
public Dictionary<int,Item> itemDic = new Dictionary<int,Item>();其中,密钥是itemID,Item是Item。这样,我就有了一种数据库来给它一些itemID,然后它就会返回适当的条目。问题是,如果我将类Tool添加到这个字典中,如果我尝试访问字典值,它将不会提供对Tool变量的访问(因为字典只指定顶级的"item“类)。
如果我创建了几个不同的继承类,我该如何设置一个字典,以允许我根据项目的itemID从字典中获得正确的类/类型
发布于 2019-01-05 17:56:07
您可以执行以下操作。
对于输入,
Dictionary<int,Item> itemDict = new Dictionary<int,Item>
{
[1] = new Item(){itemID = 2},
[2] = new Tool(){itemID=3, toolDurability=4}
};你可以的
foreach(KeyValuePair<int, Item> entry in itemDict)
{
switch(entry.Value)
{
case Tool tool:
Console.WriteLine(tool.toolDurability);
break;
case Item item:
Console.WriteLine(item.itemID);
break;
}
}https://stackoverflow.com/questions/54050761
复制相似问题