2016-11-22 57 views
-1

在爲RPG遊戲定義庫存系統時,我遇到了一個奇怪的問題。所以,我想要做的是添加一個玩家從商店中獲得的物品。在添加時,我確保不要超過重量限制,如果它已經在我的庫存包中,將增加物品的數量,否則我會明白地添加物品。IntelliSens在更新不可更改的值時未檢測到類型屬性

到目前爲止,這看起來相當健全。我的問題是當我更新我的抽象類時,IntelliSens試圖告訴我,我沒有爲我正在使用的類型定義該屬性。實際上,它找不到抽象類的任何屬性。可能是一個很糟糕的錯誤,但我已經在這個問題上困擾了很長時間,我希望得到一些支持!

UPDATE

這裏的編譯錯誤:類型 'InventoryItem' 不包含字段 '量' .. \ InventoryItems.fs 188件

[<AbstractClass>] 
    type InventoryItem() = 

    abstract member ItemName : string 

    abstract member ItemDescription : string 

    abstract member ItemWeight : float<kg> 

    abstract member ItemPrice : float<usd> 

    abstract member Quantity : int with get, set 


    let makeBagItemsDistinct (bag: InventoryItem array) = 
    bag |> Seq.distinct |> Seq.toArray 

    type Inventory = { 
     Bag : InventoryItem array 
     Weight: float<kg> 
    } 

    with 
     member x.addItem (ii: InventoryItem): Inventory = 
      if x.Weight >= MaxWeight <> true then x 
      elif (x.Weight + ii.ItemWeight) >= MaxWeight then x 
      else 
       let oItemIndex = x.Bag |> Array.tryFindIndex(fun x -> x = ii) 
       match oItemIndex with 
       | Some index -> 
        // There already an item of this type in the bag 
        let item = x.Bag |> Array.find(fun x -> x = ii) 
        let newBag = 
         x.Bag 
         |> Array.filter((<>) item) 
         |> Array.append [| { item with Quantity = item.Quantity +ii.Quantity |] 
         |> makeBagItemsDistinct 

        let inventory = { x with Bag = newBag } 
        { inventory with Weight = inventory.Weight + item.ItemWeight } 
       | None -> 
        let newBag = x.Bag |> Array.append [|ii|] |> makeBagItemsDistinct 
        let inventory = { x with Bag = newBag } 
        { inventory with Weight = inventory.Weight + ii.ItemWeight } 
+1

首先,您的縮進看起來不正確,請更正它。其次,請解釋你所得到的錯誤,在何處,何時或以何種方式知道「它不工作」。 –

+1

我做了一些修改@FyodorSoikin。就像我之前提到的,編譯器似乎沒有在InventoryItem抽象類 –

+1

中看到我的數量字段您的縮進仍然處於關閉狀態。而「似乎沒有看到」不是一個問題的好描述。 –

回答

3

with keyword作品只記錄。你正試圖在課堂上使用它。

如果您希望始終在變更上覆制InventoryItem,您可能想要切換到record,就像您已在使用Inventory一樣。

+0

如果我還想更新一個抽象類,我該怎麼去?我明白你在說什麼,但肯定有,有辦法嗎? –

+0

如果您需要複製更改,則可以使用抽象的「With」方法克隆對象,並具有可選參數以更改克隆中的某些字段。但是每個孩子課都必須實施自己的「With」方法。這是很多樣板。如果不需要C#interop,我會重新考慮使用抽象類,甚至是類。 – TheQuickBrownFox

+0

嗯,遇到此:https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/object-expressions 這將比你提供給我更好的答案。這正是我尋找的功能。我明白爲什麼在F#中使用DU和記錄很棒,但我正在尋找一個覆蓋我的類型創建的答案。 –