【发布时间】:2017-09-25 15:59:26
【问题描述】:
我不确定用什么技术术语来描述这种情况,所以这是我的情况。
上下文:
我正在为游戏设计一个物品系统。目前,存在一个 BaseGameItem 类,其中包含 Id、名称、图标等基本参数... 到目前为止,还有另一个派生自它的类,称为 PickupItem,它实现了 IPickupItem。在我尝试通过 Item Spawner 初始化这些对象之前,一切似乎都很好。
关键思想是,存在一个持久性数据库, spawner 是指在初始化对象时,它会继续 吐出完全初始化的对象,如图:
/// <summary>
/// Initialize Game Item:
/// Given an Item ID, constructs a BaseGameItem object and returns it to instigator.
/// Refers to ItemInfoTable to initialize object parameters.
/// </summary>
/// Paramater - Int ID: The provided Item ID
/// Parameter - out BaseGameItem Item: The constructed object returned to the instigator.
public static void InitializeGameItem(int id, out BaseGameItem item)
{
FItemInfoData itemInfoData = ItemTable.Find(x => x.ItemID == id);
if(itemInfoData.ItemID != id)
{
itemInfoData = ItemTable[0];
}
// Check if item is a Pickup. If so, then item is returned as a PickupPlaceable.
// Otherwise, initialize to BaseGameItem.
item = itemInfoData.IsPickupItem ? new PickupPlaceable() : new BaseGameItem();
item.SetItemName(itemInfoData.ItemName);
item.SetItemDescription(itemInfoData.ItemDescription);
item.SetItemIcon(itemInfoData.ItemIcon);
item.SetItemMesh(itemInfoData.ItemMesh);
}
我的问题如下:
- 为了知道我应该返回哪个类或该项目正在实现什么接口,我在数据库中添加了一个布尔值来检查它是否是一个 Pickup 对象。这是一个明智的决定吗?如果您能指导我阅读此类场景中使用的文章或设计模式,我将不胜感激。
- 然而,我主要关心的是返回类型。我正在使用 out 关键字并输出 BaseGameItem 对象。但是,在我的三元条件下,我可以将其初始化为派生的 Pickup 项目。函数输出是否会将其转换为 BaseGameItem,从而失去所有拾取功能?还是它将任何派生类解释为有效的返回类型?
- 如果对象被返回为 BaseGameItem 无论如何,接收者是否应该知道他们必须将其强制转换为派生类?如何解决这个问题,我是否只是在初始化函数中返回一个布尔值,指示它是一个 Pickup,以便接收器知道何时适当地投射?
【问题讨论】:
-
实际运行代码时发生了什么?
-
我觉得这个问题更适合Code Review
-
可能值得注意的是,您在施放时不会失去对象的功能;您只会失去对功能的访问权限。
标签: c# inheritance unity3d interface polymorphism