我不確定用什麼技術術語來描述這種情況,所以這裏是我的情況。C#:函數返回類型覆蓋對象轉換嗎?
語境:
我設計一個項目系統遊戲。目前,存在一個包含基本參數(如Id,名稱,圖標等)的BaseGameItem類... 迄今爲止,還存在從它派生的另一個類,稱爲PickupItem,它實現了IPickupItem。所有似乎都很好,直到我嘗試通過Item 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);
}
我的問題如下:
- 爲了知道我應該返回哪個類或項目是實現什麼接口ing,我在數據庫中包含一個布爾值,檢查它是否是Pickup對象。這是一個明智的決定嗎?如果您能指導我閱讀這種場景中使用的文章或設計模式,我將非常感激。
- 但我主要關心的是返回類型。我使用out關鍵字並輸出一個BaseGameItem對象。但是,在我的三元條件下,我可以將其初始化爲派生Pickup項目。函數輸出是否會將其強制轉換爲BaseGameItem,並因此會丟失所有拾取功能?或者它是否將任何派生類解釋爲有效的返回類型?
- 如果將對象作爲BaseGameItem返回,不管接收者是否應該知道他們必須將其轉換爲派生類?如何解決這個問題,我是否簡單地返回一個布爾值,指示它是初始化函數內的Pickup,以便接收者知道何時適當地進行轉換?
當你真正運行的代碼發生了什麼事? – Servy
我認爲這個問題更適合於[代碼評論](https://codereview.stackexchange.com/) – Xiaoy312
值得注意的是,當你投射時你不會失去對象上的功能;你只是失去了訪問功能。 –