C# 在if/else中声明派生类,而不重复基类字段
我目前正在尝试从json字符串接收的数据填充字典 我目前的做法是:C# 在if/else中声明派生类,而不重复基类字段,c#,inheritance,C#,Inheritance,我目前正在尝试从json字符串接收的数据填充字典 我目前的做法是: public class Item { public class BaseItem { public int id; public int level; } public class Armor : BaseItem { public int durability; } public class Weapon : BaseItem {
public class Item {
public class BaseItem {
public int id;
public int level;
}
public class Armor : BaseItem {
public int durability;
}
public class Weapon : BaseItem {
public int damage;
}
}
foreach (JsonObject jsonObject in jsonArray) {
if (jsonObject["armor"] != null) {
var item = new Item.Armor();
item.durability = jsonObject["armor"]["durability"];
} else if (jsonObject["weapon"] != null) {
var item = new Item.Weapon();
item.damage = jsonObject["weapon"]["damage"];
} else {
var item = new Item.BaseItem();
}
item.itemID = jsonObject["id"];
item.level = jsonObject["level"];
Item.data.Add(item.itemID, item);
}
不幸的是,这无法编译,因为我在if/else语句中声明了'item'
在不为每种项目类型定义基类字段的情况下,有什么方法可以做到这一点吗?我会在您的
if
语句之外声明项目
foreach (JsonObject jsonObject in jsonArray) {
Item.BaseItem item;
if (jsonObject["armor"] != null) {
item = new Item.Armor();
((Item.Armor)item).durability = jsonObject["armor"]["durability"];
} else if (jsonObject["weapon"] != null) {
item = new Item.Weapon();
((Item.Weapon)item).damage = jsonObject["weapon"]["damage"];
} else {
item = new Item.BaseItem();
}
item.itemID = jsonObject["id"];
item.level = jsonObject["level"];
Item.data.Add(item.itemID, item);
}
以davisoa的答案为基础构建,但仍然不需要强制转换:记住,可以对一个对象有多个引用。耶,多形性
foreach (JsonObject jsonObject in jsonArray)
{
Item.BaseItem item;
if (jsonObject["armor"] != null)
{
Item.Armor armor = new Item.Armor();
armor.durability = jsonObject["armor"]["durability"];
item = armor;
}
else if (jsonObject["weapon"] != null)
{
Item.Weapon weapon = new Item.Weapon();
weapon.damage = jsonObject["weapon"]["damage"];
item = weapon;
}
else
{
item = new Item.BaseItem();
}
item.itemID = jsonObject["id"];
item.level = jsonObject["level"];
Item.data.Add(item.itemID, item);
}
我已经尝试过了,但是我收到了以下错误:“TypeItem.BaseItem'不包含
耐久性的定义”,并且没有类型为
Item.BaseItem'的扩展方法耐久性”。可以找到BaseItem“然后您需要强制转换子属性的每个特定用法是否可以发布一个示例?”)我更新了答案,以显示如何将项
强制转换为适当的类型以访问子属性。