在为RPG游戏定义库存系统时,我遇到了一个奇怪的问题。所以,我要做的是添加玩家从商店获得的物品。在添加时,我确保不要超过重量限制并且如果它已经在我的库存包中将增加项目的数量,否则我将明显地添加该项目。
到目前为止,这看起来非常合理。我的问题是当我更新我的抽象类时,IntelliSens试图告诉我,我没有为我正在使用的类型定义该属性。实际上,它找不到抽象类的任何属性。可能是一个错误的错误,但是我已经在这个问题上抓了很长时间了,我想得到一些支持!
更新
这是编译错误:类型'InventoryItem'不包含字段'Quantity'.. \ 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 }
答案 0 :(得分:3)
with keyword仅适用于记录。你正试图在课堂上使用它。
如果您希望始终在更改时复制InventoryItem
,则可能需要切换为record,就像您已使用Inventory
一样。